import matplotlib.pyplot as plt
fig=plt.figure()
fig2=plt.subplots()
fig3,axs=plt.subplots(2,2)
plt.show()
<Figure size 640x480 with 0 Axes>
fig,ax=plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
[<matplotlib.lines.Line2D at 0x123efb690>]
Axes 绘图方法,matplotlib.pyplot 模块中有一个相应的函数可以在“当前”轴上执行该绘图,如果它们尚不存在,则会创建该轴(及其父图形
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
[<matplotlib.lines.Line2D at 0x123f33690>]
一个完整的绘画
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.show()
#上述代码相当于
fig,ax=plt.subplots()
ax.plot([1,2,3,4],[1,4,2,3])
plt.show()
import pandas as pd
import numpy as np
a=pd.DataFrame(np.random.rand(4,5),columns=list('abcde'))
a_asarray=a.values
print(a)
print(a_asarray)
a b c d e
0 0.942851 0.469160 0.163871 0.383466 0.482122
1 0.153815 0.297769 0.402677 0.449713 0.501791
2 0.084304 0.471720 0.446233 0.112047 0.172477
3 0.648961 0.762354 0.651969 0.436571 0.151777
[[0.94285104 0.46915987 0.16387077 0.38346593 0.4821217 ]
[0.15381521 0.2977688 0.4026774 0.44971345 0.50179147]
[0.08430377 0.47171985 0.44623296 0.11204723 0.172477 ]
[0.64896052 0.76235361 0.65196889 0.43657115 0.15177734]]
b=np.matrix([[1,2],[3,4]])
b_asarray=np.asanyarray(b)
print(b)
print(b_asarray)
[[1 2]
[3 4]]
[[1 2]
[3 4]]
## oo方法
x=np.linspace(0,2,100)
fig,ax=plt.subplots()
ax.plot(x,x,label='linear')
ax.plot(x,x**2,label='quadratic')
ax.plot(x,x**3,label='cubic')
ax.set_xlabel('x_label')
ax.set_ylabel('y_label')
ax.set_title("Simple label")
ax.legend() ## 添加图例
plt.show()
def my_plotter(ax,data1,data2,param_dict):
out=ax.plot(data1,data2,**param_dict)
return out
data1,data2,data3,data4=np.random.randn(4,100)
fig,ax=plt.subplots(1,1)
my_plotter(ax,data1,data2,{'marker':'x'})
plt.show()
fig,(ax1,ax2)=plt.subplots(1,2)
data1, data2, data3, data4 = np.random.randn(4, 100)
my_plotter(ax1,data1,data2,{'marker':'x'})
my_plotter(ax2,data3,data4,{'marker':'o'})
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
y=np.random.rand(100000)
y[50000:]*=2
y[np.linspace(1,np.log10(5000),400).astype(int)]=-1
mpl.rcParams['path.simplify']=True
mpl.rcParams['path.simplify_threshold']=0.0
plt.plot(y)
plt.show()
Matplotlib 默认为 1/9 的保守简化阈值
x=[1,2,3,4]
y=[1,3,3,2]
plt.plot(x, y, markevery=10)
[<matplotlib.lines.Line2D at 0x126b66b90>]
使用 pyplot 生成可视化非常快
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
plot() 命令提供单个列表或数组,matplotlib 会假定它是一个 y 值序列,并自动为你生成 x 值.
默认的 x 向量的长度与 y 相同,但从 0 开始,因此 x 数据为 [0, 1, 2, 3]
import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,4,9,16])
plt.show()
添加颜色
import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,4,9,16],'ro')
plt.axis([0,6,0,20])
plt.show()
axis() 命令采用 [xmin, xmax, ymin, ymax] 列表来指定x、y轴的范围
import matplotlib.pyplot as plt
import numpy as np
t=np.arange(0.,5.,0.2)
plt.plot(t,t,'r--',t,t**2,'bs',t,t**3,'g^')
plt.show()
数据格式允许你使用字符串访问特定变量。例如numpy.recarray 或 pandas.DataFrame
atplotlib 允许你为这样的对象提供 data 关键字参数,并使用与这些变量对应的字符串生成图
data={'a':np.arange(50),
'c':np.random.randint(0,50,50),
'd':np.random.randn(50),
}
data['b']=data['a']+10*np.random.randn(50)
data['d']=np.abs(data['d'])*100
plt.scatter('a','b',c='c',s='d',data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
import matplotlib.pyplot as plt
names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]
plt.figure(figsize=(9, 3))
## (131) 表示将绘图区域划分为一个 1x3 的网格(1 行 3 列),并选择当前要绘制的子图为第 1 个子图
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()
线宽、虚线样式、反走样等
使用关键字参数
x=[1, 2, 3, 4]
plt.plot(x,linewidth=3.0) #设置宽限
plt.ylabel('some numbers')
plt.show()
使用 Line2D 的setter 方法
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
line, = plt.plot(x, y, '-')
line.set_antialiased(False) # 关闭antialiasing
print(line) # >>> Line2D(_child0)
plt.show()
Line2D(_child0)
要获取可设置属性的列表,可以使用一行或多行作为参数调用 setp() 函数
import matplotlib.pyplot as plt
lines = plt.plot([1, 2, 3])
print(plt.setp(lines))
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image
alpha: scalar or None
animated: bool
antialiased or aa: bool
clip_box: `~matplotlib.transforms.BboxBase` or None
clip_on: bool
clip_path: Patch or (Path, Transform) or None
color or c: color
dash_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'}
dash_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'}
dashes: sequence of floats (on/off ink in points) or (None, None)
data: (2, N) array or two 1D arrays
drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
figure: `~matplotlib.figure.Figure`
fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'}
gapcolor: color or None
gid: str
in_layout: bool
label: object
linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw: float
marker: marker style string, `~.path.Path` or `~.markers.MarkerStyle`
markeredgecolor or mec: color
markeredgewidth or mew: float
markerfacecolor or mfc: color
markerfacecoloralt or mfcalt: color
markersize or ms: float
markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
mouseover: bool
path_effects: list of `.AbstractPathEffect`
picker: float or callable[[Artist, Event], tuple[bool, dict]]
pickradius: float
rasterized: bool
sketch_params: (scale: float, length: float, randomness: float)
snap: bool or None
solid_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'}
solid_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'}
transform: `~matplotlib.transforms.Transform`
url: str
visible: bool
xdata: 1D array
ydata: 1D array
zorder: float
None
使用 setp() 命令
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
lines = plt.plot(x, y)
plt.step(x,y,color='r',linewidth=2.0)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure()
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
import matplotlib.pyplot as plt
plt.figure(1) # 第一个图形
plt.subplot(211) # 第一个图形中的第1个子图
plt.plot([1, 2, 3])
plt.subplot(212) # 第一个图形中的第2个子图
plt.plot([4, 5, 6])
plt.figure(2) # 第二个图形
plt.plot([4, 5, 6]) # 创建默认子图,默认subplot(111)
plt.figure(1) # 当前图形为figure 1; 由于subplot(212) 在211后面定义,所以当前子图为subplot(212)
plt.subplot(211) # 定义当前子图为subplot(211)
plt.title('Easy as 1, 2, 3') # 给211子图定义标题
plt.show()
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# 柱状图
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
plt.xlabel('my data', fontsize=14, color='red')
Text(0.5, 0, 'my data')
注释文本
text() 命令的使用可以将文本放置在轴上的任意位置
文本的一个常见用途是对绘图的某些特征进行注释,并且 annotate() 方法提供了帮助功能使注释变得容易
在注释中,需要考虑两点:参数 xy 表示的被注释位置和文本 xytext 的位置,这两个参数都是 (x, y) 元组
import matplotlib.pyplot as plt
import numpy as np
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
'''
local max:注释的内容
xy:箭头头的坐标
xytext:注释内容的起始位置
arrowprops:设置箭头的一些属性,颜色、宽度等
'''
plt.ylim(-2, 2)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
y=np.random.normal(loc=0.5,scale=4,size=1000)
y=y[(y>0)&(y<1)]
y.sort()
x=np.arange(len(y))
plt.figure()
#linear
plt.subplot(121)
plt.plot(x,y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(122)
plt.plot(x,y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('data.png')
print(img)
[[0.40784314 0.40784314 0.40784314 ... 0.42745098 0.42745098 0.42745098]
[0.4117647 0.4117647 0.4117647 ... 0.42745098 0.42745098 0.42745098]
[0.41960785 0.41568628 0.41568628 ... 0.43137255 0.43137255 0.43137255]
...
[0.4392157 0.43529412 0.43137255 ... 0.45490196 0.4509804 0.4509804 ]
[0.44313726 0.44313726 0.4392157 ... 0.4509804 0.44705883 0.44705883]
[0.44313726 0.4509804 0.4509804 ... 0.44705883 0.44705883 0.44313726]]
Matplotlib 已将每个通道的 8 位数据重新缩放为 0.0 到 1.0 之间的浮点数据,每个内部列表代表一个像素
对于 RGB 图像,有 3 个值。由于它是黑白图像,因此 R、G 和 B 都相似
对于 RGBA(其中 A 是 alpha 或透明度),每个内部列表有 4 个值,而简单的亮度图像只有一个值(因此只是一个 2-D 数组,而不是 3-D 数组)
## 将 numpy 数组绘制为图像
Matplotlib 中,可以使用 imshow() 函数来渲染图像数据生成的numpy数组
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('data.png')
img
#将伪彩色方案应用于图像图
lum_img = np.expand_dims(img, axis=2)
plt.imshow(lum_img)
plt.show()
## 增加亮色
plt.imshow(lum_img,cmap='hot')
<matplotlib.image.AxesImage at 0x1268284d0>
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('nipy_spectral')
加入色标
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('data.png')
img
#将伪彩色方案应用于图像图
lum_img = np.expand_dims(img, axis=2)
plt.imshow(lum_img)
plt.colorbar()
plt.show()
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('data.png')
lum_img = np.expand_dims(img, axis=2)
plt.hist(lum_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
plt.show()
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('data.png')
lum_img = np.expand_dims(img, axis=2)
fig = plt.figure()
a = fig.add_subplot(1, 2, 1)
imgplot = plt.imshow(lum_img)
a.set_title('Before')
plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
a = fig.add_subplot(1, 2, 2)
imgplot = plt.imshow(lum_img, clim=(0.0, 0.7))
# 也可以:
# imgplot = plt.imshow(lum_img)
# imgplot.set_clim(0.0, 0.7)
a.set_title('After')
plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
plt.show()
import matplotlib.pyplot as plt
from PIL import Image
img = Image.open('data.png')
img.thumbnail((64, 64), Image.LANCZOS)
imgplot = plt.imshow(img)
plt.show()
imgplot = plt.imshow(img, interpolation="nearest")
双三次插值(bicubic)
imgplot = plt.imshow(img, interpolation="bicubic")
import numpy as np
import matplotlib.pyplot as plt
data = {'Barton LLC': 109438.50,
'Frami, Hills and Schmidt': 103569.59,
'Fritsch, Russel and Anderson': 112214.71,
'Jerde-Hilpert': 112591.43,
'Keeling LLC': 100934.30,
'Koepp Ltd': 103660.54,
'Kulas Inc': 137351.96,
'Trantow-Barrows': 123381.38,
'White-Trantow': 135841.99,
'Will LLC': 104437.60}
group_data = list(data.values())
group_names = list(data.keys())
group_mean = np.mean(group_data)
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
plt.show()
import matplotlib.pyplot as plt
print(plt.style.available)
['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-v0_8', 'seaborn-v0_8-bright', 'seaborn-v0_8-colorblind', 'seaborn-v0_8-dark', 'seaborn-v0_8-dark-palette', 'seaborn-v0_8-darkgrid', 'seaborn-v0_8-deep', 'seaborn-v0_8-muted', 'seaborn-v0_8-notebook', 'seaborn-v0_8-paper', 'seaborn-v0_8-pastel', 'seaborn-v0_8-poster', 'seaborn-v0_8-talk', 'seaborn-v0_8-ticks', 'seaborn-v0_8-white', 'seaborn-v0_8-whitegrid', 'tableau-colorblind10']
plt.style.use('fivethirtyeight') #样式设置成fivethirtyeight
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
<BarContainer object of 10 artists>
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
print(fig.canvas.get_supported_filetypes())
'''
{'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group',
'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format',
'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics',
'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap',
'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics',
'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}
'''
{'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format', 'webp': 'WebP Image Format'}
"\n{'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', \n'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', \n'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', \n'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', \n'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', \n'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}\n"
# 保存图形
fig.savefig('山月.png', transparent=False, dpi=80, bbox_inches="tight")