如何将单独的Pan das DataFrames绘制为子图?

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

我有一些Pandas DataFrames共享相同的值规模,但具有不同的列和索引。在调用df.plot()时,我会得到单独的情节图像。我真正想要的是将它们全部放在与次要情节相同的情节中,但遗憾的是我没有想出一个如何并且非常欣赏一些帮助的解决方案。

python matplotlib pandas
6个回答
178
投票

您可以使用matplotlib手动创建子图,然后使用ax关键字在特定子图上绘制数据框。例如,对于4个子图(2x2):

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)

df1.plot(ax=axes[0,0])
df2.plot(ax=axes[0,1])
...

这里axes是一个包含不同子图轴的数组,你可以通过索引axes来访问它。 如果你想要一个共享的x轴,那么你可以提供sharex=Trueplt.subplots


39
投票

你可以看到e.gs.在documentation展示joris答案。同样从文档中,您还可以在pandas subplots=True函数中设置layout=(,)plot

df.plot(subplots=True, layout=(1,2))

您还可以使用fig.add_subplot(),它采用子图网格参数,如221,222,223,224等,如后here中所述。在this ipython notebook中可以看到关于pandas数据框的情节的好例子,包括子图。


14
投票

您可以使用熟悉的Matplotlib样式调用figuresubplot,但您只需使用plt.gca()指定当前轴。一个例子:

plt.figure(1)
plt.subplot(2,2,1)
df.A.plot() #no need to specify for first axis
plt.subplot(2,2,2)
df.B.plot(ax=plt.gca())
plt.subplot(2,2,3)
df.C.plot(ax=plt.gca())

等等...


3
投票

你可以用这个:

fig = plt.figure()
ax = fig.add_subplot(221)
plt.plot(x,y)

ax = fig.add_subplot(222)
plt.plot(x,z)
...

plt.show()

2
投票

你可能根本不需要使用熊猫。这是猫频率的matplotlib图:

enter image description here

x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

f, axes = plt.subplots(2, 1)
for c, i in enumerate(axes):
  axes[c].plot(x, y)
  axes[c].set_title('cats')
plt.tight_layout()

1
投票

在上面的@joris响应的基础上,如果您已经建立了对子图的引用,您也可以使用该引用。例如,

ax1 = plt.subplot2grid((50,100), (0, 0), colspan=20, rowspan=10)
...

df.plot.barh(ax=ax1, stacked=True)
© www.soinside.com 2019 - 2024. All rights reserved.