我目前正在尝试创建一个包含四个子图的图形。在每个子图中,我想绘制一个带有误差线的数据集。但是,对于其中一个数据集,我还想在同一个子图中绘制一个多项式拟合该数据。我的代码如下所示:
import matplotlib.pyplot as plt
import numpy as np
# define four sets of data here: x1, y1, yerr1, x2, y2, yerr2, etc...
fit1 = np.poly1d(np.polyfit(x1,y1,1))
xrange = np.linspace(min(x1), max(x1), num = 1000)
f, axarr = plt.subplots(2,2)
axarr[0,0].plot(xrange, fit1(xrange))
axarr[0,0].errorbar(x1, y1, yerr = yerr1, fmt = 'r.')
# and for the rest just the errorbar portion
plt.show()
但是,我得到的结果如下:
因此,我在第一个子图中拟合了数据集 1,在第二个子图中没有任何拟合,在第三个子图中拟合了数据集 1 和 2,在第四个子图中拟合了数据集 1 和 2。有什么方法可以让我得到我想要的东西(即适合子图 1 的数据集 1,适合子图 2 的数据集 2,等等)?
谢谢!
最佳答案
从你的代码中看不出你在做什么。但是您可以调用 plt.subplot(2,2,1)
然后对左上图执行所有绘图命令,然后调用 plt.subplot(2,2,2)
然后是你的绘图命令到下一个子图等。
Matplotlib 存储您的最后一个子图(或轴对象),所有绘图命令都绘制到最后一个子图中。
plt.subplot(2,2,1)
plt.plot(data_x,data_y,'o')
plt.plot(data_x,fit_y,'-')
plt.subplot(2,2,2)
plt.plot(...
关于python - 单个子图 Pyplot 上的多种绘图类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34213137/