2

我需要在一列中从两个 DataFrame 中绘制几列(每个图两列或多列),共享 x 轴。所有数据都有相同的索引。从 [ 1 ]
中获取和修改的示例:

 df = DataFrame(randn(1000, 4), index=date_range('1/1/2000', periods=1000), columns=list('AB'))
 df2 = DataFrame(randn(1000, 4), index=df.index, columns=list('CD'))
 df = df.cumsum()
 df2 = df.cumsum()

 fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True)
 df['A'].plot(ax=axes[0,0])
 df2['C'].plot(ax=axes[0,0])
 df['B'].plot(ax=axes[1,0])
 df2['D'].plot(ax=axes[1,0])

运行这个我得到:IndexError: too many indices这是一个错误还是我错过了什么?

当我改变ncols=2时,一切都很好,但有两个额外的空白图。

我可以使用其他解决方案,但上面看起来更好:

ax1 = subplot(211)
df['A'].plot()
df2['C'].plot()

ax2 = subplot(212, sharex=ax1)
df['B'].plot()
df2['D'].plot()
4

1 回答 1

3

这是因为axes是一维 ndarray 所以axes[0, 0]不是有效索引。只有 0 和 1 有效。将绘图代码更改为:

df['A'].plot(ax=axes[0])
df2['C'].plot(ax=axes[0])
df['B'].plot(ax=axes[1])
df2['D'].plot(ax=axes[1])

你也可以做

fig, (ax1, ax2) = subplots(2, 1, sharex=True)

df['A'].plot(ax=ax1)
df2['C'].plot(ax=ax1)
df['B'].plot(ax=ax2)
df2['D'].plot(ax=ax2)
于 2013-08-23T20:59:04.430 回答