Matplotlib简单画图(二) -- subplot

# 导入库
import pandas as pd
import numpy as np
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
# 等差数列50个值
x = np.linspace(0.0, 5.0)
# 生成两个y轴坐标
y1 = np.sin(np.pi*x)
y2 = np.sin(np.pi*x*2)
# 画线
plt.plot(x, y1, 'b--', label='sin(pi*x)')
plt.ylabel('y1 value')
plt.plot(x, y2, 'r--', label='sin(pi*2x)')
plt.ylabel('y2 value')
plt.xlabel('x value')
plt.title('this is x-y value')
# 显示线的label
plt.legend()

这里写图片描述

使用subplot画子图

# 两行一列的图,第三个参数为第几个图
plt.subplot(2,1,1)
# 画线
plt.plot(x, y1, 'b--')
plt.ylabel('y1')
# 切换到第二个子图
plt.subplot(2,1,2)
# 画线
plt.plot(x,y2,'r--')
plt.ylabel('y2')
plt.xlabel('x')

这里写图片描述

# 两行两列
plt.subplot(2,2,1)#也可以直接plt.subplot(221)
plt.plot(x, y1, 'b--')
plt.ylabel('y1')
plt.subplot(2,2,2)
plt.plot(x,y2,'r--')
plt.ylabel('y2')
plt.xlabel('x')
plt.subplot(2,2,3)
plt.plot(x, y1, 'b*')

这里写图片描述

subplots

a = plt.subplots()
type(a)
tuple
a[0],a[1]
(<matplotlib.figure.Figure at 0x1f871bd0e10>,
 <matplotlib.axes._subplots.AxesSubplot at 0x1f871c31240>)
figure, ax = plt.subplots(2,2)
figure

这里写图片描述

# ax是一个数组,可以通过ax访问子图
ax
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000001F871F49358>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001F871F7DEF0>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x000001F871FB7EF0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000001F871FEEF60>]], dtype=object)
ax[0][0].plot(x, y1)
ax[0][1].plot(x, y2)
figure

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39778570/article/details/81138555