Matploblib介绍
Matplotlib 是Python中类似 MATLAB 的绘图工具,熟悉 MATLAB 也可以很快的上手 Matplotlib;
matplotlib概念介绍:
Figure
在任何绘图之前,我们需要一个Figure对象,可以理解成我们需要一张画布才能开始绘图
import matplotlib.pyplot as plt
fig = plt.figure()
Axes
在拥有Figure对象之后,在作画前我们还需要轴,没有轴的话就没有绘图基准,所以需要添加Axes,Axes代表的则是纸中的一片区域(当然可以有多个区域,这是后续要说到的subplots)
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlim=[0.5, 3.5], ylim=[-2, 6], title='An Example Axes',
ylabel='Y-Axis', xlabel='X-Axis')
plt.show()
通过图片可知:
1.ax.set设置坐标轴名称(ylabel,xlabel)及取值范围(xlim,ylim)还可以增加主题(title)
思考:fig.add_subplot(111)中111代表什么?
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
plt.show()
通过图片可知:
1.生成4个相等的区域;4=22
2.通过fig.add_subplot(2, 2, 1)或fig.add_subplot(221)的方式生成Axes,前面两个参数确定了面板的划分,例如 2, 2会将整个面板划分成 4 块区域,第三个参数取值范围是 [1, 22] 表示第几个区域
sublplot函数
axes 采用我们常用二维数组的形式访问;
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0,0].set(title='Upper Left')
axes[0,1].set(title='Upper Right')
axes[1,0].set(title='Lower Left')
axes[1,1].set(title='Lower Right')
plt.show()
示例
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0=axes[0,0]
ax0.set(title='Upper Left')
ax1=axes[0,1]
ax1.set(title='Upper Right')
ax2=axes[1,0]
ax2.set(title='Lower Left')
ax3=axes[1,1]
ax3.set(title='Lower Right')
x = [1, 2, 3, 4]
y1 = [1, 2, 3, 4]
y2 = [1, 4, 9, 16]
y3 = [2, 6, 6, 8]
y4 = [1, -3, 5, 7]
ax0.plot(x, y1, 'r')
ax1.plot(x, y2)
ax2.plot(x, y3,'g')
ax3.plot(x, y4,'y')
plt.show()
subplots_adjust函数
plt.subplots_adjust():调整子图间的距离
plt.subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)
参数解释:
left:默认为0.125,子图(subplot)距画板(figure)左边的距离
right:默认为0.9,子图(subplot)距画板(figure)右边的距离
bottom:默认为0.1,子图(subplot)距画板(figure)底部的距离
top:默认为0.9,子图(subplot)距画板(figure)顶部的距离
wspace:默认为0.2,子图水平间距
hspace:默认为0.2,子图垂直间距
示例
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y1 = [1, 2, 2, 4]
y2 = [1, 4,8, 16]
y3 = [2, 6, 6,9]
y4 = [1, -3, 6, 7]
plt.figure()
plt.subplot(221)
plt.plot(x, y1, 'r')
plt.subplot(222)
plt.plot(x, y2)
plt.subplot(223)
plt.plot(x, y3,'g')
plt.subplot(224)
plt.plot(x, y4,'y')
plt.subplots_adjust(hspace=0.5, wspace=0.5)
plt.show()