matplotlib一张画布中有多个子图的绘图实践

2021-01-31  本文已影响0人  LabVIEW_Python

上一节了解了一张画布中只有一个子图绘图方法后,现在来讨论一张画布中有多个子图的绘图实践,是实现方式也是分:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.linspace(0,2,200)

fig, ax = plt.subplots(2,2) # 手动创建一个figure和四个ax对象

plt.subplot(2,2,1) # Add a subplot to the current figure
plt.plot(x, x, color='blue', label='Linear') # 绘制第一个子图
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.legend() # 开启图例

plt.subplot(2,2,2)
plt.plot(x, x**2, color='red', label='Quadratic') # 绘制第二个子图
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.legend() # 开启图例

plt.subplot(2,2,3)
plt.plot(x, x**3, color='green', label='Cubic') # 绘制第三个子图
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.legend() # 开启图例

plt.subplot(2,2,4)
plt.plot(x, np.log(x), color='purple', label='log') # 绘制第四个子图
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.legend() # 开启图例

fig.suptitle("Simple plot demo with one figure and one axes")

plt.show() # 展示绘图

OO风格范例代码如下所示

import matplotlib.pyplot as plt 
import numpy as np 

x = np.linspace(0,2,200)

fig, ax = plt.subplots(2,2) # 手动创建一个figure和四个ax对象

ax[0,0].plot(x, x, color='blue', label='Linear') # 绘制第一个子图
ax[0,0].set_xlabel('x-axis')
ax[0,0].set_ylabel('y-axis')
ax[0,0].legend() # 开启图例

ax[0,1].plot(x, x**2, color='red', label='Quadratic') # 绘制第二个子图
ax[0,1].set_xlabel('x-axis')
ax[0,1].set_ylabel('y-axis')
ax[0,1].legend() # 开启图例

ax[1,0].plot(x, x**3, color='green', label='Cubic') # 绘制第三个子图
ax[1,0].set_xlabel('x-axis')
ax[1,0].set_ylabel('y-axis')
ax[1,0].legend() # 开启图例

ax[1,1].plot(x, np.log(x), color='purple', label='log') # 绘制第四个子图
ax[1,1].set_xlabel('x-axis')
ax[1,1].set_ylabel('y-axis')
ax[1,1].legend() # 开启图例

fig.suptitle("Simple plot demo with one figure and one axes")

plt.show() # 展示绘图
运行结果: 多个子图的绘图实践
上一篇下一篇

猜你喜欢

热点阅读