1.简介
Matplotlib是Python中最常用的可视化工具之一,可以非常方便地创建海量类型地2D图表和一些基本的3D图表。Matplotlib最早是为了可视化癫痫病人的脑皮层电图相关的信号而研发,因为在函数的设计上参考了MATLAB,所以叫做Matplotlib。Matplotlib首次发表于2007年,是由John D. Hunter发起,在开源和社区的推动下,现在在基于Python的各个科学计算领域都得到了广泛应用。
2.基础包导入
3 基础对象
下面给大家介绍画布:figure;画布中带坐标系(coordinate)的绘图区域:axes。
In [3]:
## 图示讲解figure ,axes
from IPython.display import Image
Image('figure-axes.jpg')
Out[3]:
In [4]:
## axes中图像的坐标轴,标签,刻度,标注等对象
Image('aexs-mat.jpg')
Out[4]:
4 画布布局
4.1 坐标体系
图像坐标:图像坐标将一张图的左下角视为原点,将图像的x方向和y方向总长度都看做1。x方向的0.2就是指20%的图像在x方向的总长,y方向0.8的长度指80%的y方向总长。fig.transFigure,ax1.transAxes
数据坐标:plot中x/y参数对应数据.
4.2 单实例 单axes - plt.plot
In [44]:
## 直接引用plt.plot,默认是在当前画布中反复增加显示新数据
## 利用numpy产生序列数据
x = np.linspace(0, 10, 100) ##numpy生成随机数 X轴对应的数组
x2 = np.linspace(10, 20, 100)
fig=plt.figure(figsize(8,4),facecolor='lightgray') ###下面是四种不同的图
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--');
plt.plot(x2, np.sin(x2), 'o')
plt.plot(x2, np.cos(x2), '*');
4.3 单实例 多axes - plt.subplot
一开始是为MATLAB工具用户设计的图形工具扩展,所以pyplot的接口更多的是MATLAB的风格;这种调用方式,都是默认在当前figure和axes上进行图形绘制和展示,状态也会一直变化。
In [8]:
for i in range(1, 7):
plt.subplot(2, 3, i)
#第一个参数为行,第二个参数为列
print plt.get_fignums
plt.text(0.5, 0.5, str((2, 3, i)),
fontsize=18, ha='center')
In [16]:
## plt.subplot里的索引引用方式【nrows, ncols, plot_number】或者 【rcp】都行
plt.subplot(211)
plt.plot(np.sin(x))
plt.subplot(212,axisbg='y')
plt.plot(np.cos(x))
Out[16]:
4.4 多实例 多axes - plt.subplots
In [22]:
#可以实例化成axes数组,可以选择共享x/y周,不必每次都重新声明生成,提高效率
fig, ax = plt.subplots(2, 3, sharex='row', sharey='col')
# axes are in a two-dimensional array, indexed by [row, col]
for i in range(2):
for j in range(3):
ax[i, j].text(0.5, 0.5, str((i, j)),
fontsize=18, ha='center')
4.5 多实例 多axes - plt.axes()
In [31]:
#画中画,前两个参数代表整个figure中left,bottom百分比,后两个参数代表轴的长度的百分比
ax1 = plt.axes(axisbg='y') # standard axes
ax2 = plt.axes([0.50, 0.50, 0.2, 0.2])
ax1.plot(x,np.sin(x))
ax2.plot(x,np.sin(x))
Out[31]:
In [34]:
plt.figure?
In [35]
# [left, bottom, width, height]
fig = plt.figure(facecolor='y')
ax1 = fig.add_axes([0, 0.5, 0.8, 0.4])
ax2 = fig.add_axes([0.1, 1.0, 0.8, 0.4])
x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x))
Out[35]:
4.6 高级模式 -plt.GridSpec
In [32]:
### 多个图像合并
grid = plt.GridSpec(2, 3, wspace=0.5, hspace=0.5)
plt.subplot(grid[0, 0])
plt.subplot(grid[0, 1:])
plt.subplot(grid[1, :2])
plt.subplot(grid[1, 2])
Out[32]:
5 简单画图
5.1 plt.plot 参数讲解
x,y,color,linestyle,maker,label,linewidth
In [50]:
## plt.plot(x, np.sin(x - 0), color='blue')
x = np.linspace(0,10,100)
plt.plot(x, np.sin(x - 0), color='blue')
# specify color by name
plt.plot(x, np.sin(x - 1), color='g')
# short color code (rgbcmyk)
plt.plot(x, np.sin(x - 2), color='0.1')
# Grayscale between 0 and 1 颜色的灰度
#plt.plot(x, np.sin(x - 3), color='#FFDD44') # Hex code (RRGGBB from 00 to FF)
#plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB tuple, values 0 to 1
plt.plot(x, np.sin(x - 5), color='chartreuse'); # all HTML color names supported
In [51]:
# For short, you can use the following codes: 线的格式
plt.plot(x, x + 4, linestyle='-') # solid
plt.plot(x, x + 5, linestyle='--') # dashed
plt.plot(x, x + 6, linestyle='-.') # dashdot
plt.plot(x, x + 7, linestyle=':'); # dotted
In[52]:
## 简写
plt.plot(x, x + 0, 'g-') # solid green
plt.plot(x, x + 1, '--c') # dashed cyan
plt.plot(x, x + 2, '-.k') # dashdot black
plt.plot(x, x + 3, ':r'); # dotted red
5.2 图形参数配置
坐标轴的取值范围 xlim,ylim,axis
坐标轴的标签:xlabel,ylabel
In [42]:
## 配置x,y轴的取值范围
plt.subplot(2,2,1)
plt.plot(x, np.sin(x))
plt.xlim(-1, 11)
plt.ylim(-1.5, 1.5)
plt.title("lim")
plt.subplot(2,2,2)
plt.plot(x, np.sin(x))
plt.axis([-1, 11, -1.5, 1.5])
plt.title("axis")
plt.subplot(2,2,3)
plt.plot(x, np.sin(x))
plt.axis('tight')
plt.title("tight",verticalalignment = "top")
plt.subplot(2,2,4)
plt.plot(x, np.sin(x))
plt.axis('equal');
plt.title("equal",verticalalignment = "top")
Out[42]:
图例显示 plot(,label='',) plt.legend()
In [43]:
## 多个序列同图显示,label表示图例,用legend()方法显示
plt.plot(x, np.sin(x), '-g', label='sin(x)')
plt.plot(x, np.cos(x), ':b', label='cos(x)')
plt.axis('equal')
plt.xlabel("xlable")
plt.ylabel("sin(x)",rotation = 'horizontal') ## vertical
## 图例显示的时候可以配置 loc-位置,frameon-边框,ncol-列数
## plt.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1) 对齐方式
plt.legend(loc='upper left', frameon=False, ncol=1)
out[43]:
axes.set 函数设定
In [57]:
## [left, bottom, width, height]
fig = plt.figure()
#ax1 = fig.add_axes([0.1, 0.6, 0.8, 0.4],xticklabels=[], ylim=(-1.2, 1.2))
#ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4],ylim=(-1.2, 1.2))
ax1 = fig.add_axes([0.1, 0.8, 0.5, 0.5])
ax2 = fig.add_axes([0, 0.1, 0.5, 0.5])
x = np.linspace(0, 10,100)
ax1.plot(x,np.sin(x))
ax2.plot(x,np.cos(x))
ax1.set(xlim=(0, 10), ylim=(-2, 2), ###轴区间范围
xlabel='x', ylabel='sin(x)', ##标题
title='AX1');
ax2.set(xlim=(0, 10), ylim=(-2, 2),
xlabel='x', ylabel='cos(x)',
title='AX2');
5.3 高级定制
显示标签 text
In [15]:
fig, ax = plt.subplots(facecolor='lightgray')
##数据的标签
ax.axis([0, 10, 0, 10])
# transform=ax.transData is the default, but we'll specify it anyway
ax.text(1, 5, ". Data: (1, 5)", transform=ax.transData)
## 实际坐标的位置 指定x与Y值
ax.text(0.5, 0.1, ". Axes: (0.5, 0.1)", transform=ax.transAxes)
## 图像的位置
ax.text(0.2, 0.2, ". Figure: (0.2, 0.2)", transform=fig.transFigure);
## 画布的位置
显示箭头 annotate
In [41]:
fig, ax = plt.subplots()
x = np.linspace(0, 20, 1000)
ax.plot(x, np.cos(x))
ax.axis('equal')
ax.annotate('local maximum', xy=(6.28, 1), xytext=(10, 4),
arrowprops=dict(facecolor='black'))
ax.annotate('local minimum', xy=(5 * np.pi, -1), xytext=(2, -6),
arrowprops=dict(arrowstyle="->",connectionstyle="angle3,angleA=0,angleB=-90"));
坐标轴刻度定制
In [24]:
ax = plt.axes()
ax.plot(np.random.rand(50))
ax.yaxis.set_major_locator(plt.NullLocator())
ax.xaxis.set_major_formatter(plt.NullFormatter())
#图像显示代码 需要从外网自动下载数据
fig, ax = plt.subplots(5, 5, figsize=(5, 5))
fig.subplots_adjust(hspace=0, wspace=0)
# Get some face data from scikit-learn
from sklearn.datasets import fetch_olivetti_faces
faces = fetch_olivetti_faces().images
for i in range(5):
for j in range(5):
ax[i,j].xaxis.set_major_locator(plt.NullLocator())
ax[i,j].yaxis.set_major_locator(plt.NullLocator())
ax[i, j].imshow(faces[10 * i + j], cmap="bone")
今天主要是介绍Matplotlip包的基础知识,下期我们将进一步学习可视化,精彩继续喔!
领取专属 10元无门槛券
私享最新 技术干货