在所有子图中使用列绘制DataFrame

问题描述 投票:6回答:1

考虑一下我有一个包含3列的pandas DataFrame。我想将这些列中的两个作为单独的子图绘制,另一个列应该出现在其他两个子图上。

为了更好地解释,请考虑这个例子

x = np.linspace(0,10,5)
y1 = 2*x
y2 = 3*x
y3 = 4*x

df = pd.DataFrame(index=x, data=zip(*[y1,y2,y3]))
df.plot(subplots=True, layout=(1,3), ylim=[0,40])

此代码显示enter image description here

哪个接近我想要的。但不完全是。我希望那个情节只有两个子图。一个是列0和1,另一个是列0和2.将每列与另一列进行比较。我得到的最接近的是

df[[1,2]].plot(subplots=True, layout=(1,2), ylim=[0,40])
plt.plot(df.index, df[0], label=0)

这给了我这张图片,其中第0列只出现在第二个子图中,而不是全部出现在第二个子图中:

enter image description here

有没有办法做到这一点?最好不要完全在熊猫之外。我知道我可以遍历第1列和第2列并使用pyplot和第0列手动绘制它们,但这只是代码太多而且我想避免这种情况,如果可能的话。

python pandas matplotlib plot
1个回答
4
投票

像这样

ax = df[[1,2]].plot(subplots=True, layout=(1,2), ylim=[0,40])

for axe in ax[0]:
    axe.plot(df.index, df[0])

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.