从具有不同y轴的pandas数据框中绘制条形图和线条

时间:2019-05-16 14:45:42

标签: python pandas matplotlib

我要绘制以下数据框。我正在尝试有2个子图,其中一个具有两个图(具有不同的y轴并共享x)

size = (20,10)
fig = plt.figure(figsize=size)
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax3 = ax2.twinx()

# the dataframe is obtained by other means, and has the following format:

Date        col1        col2    col3    col4        
2017-06-30  7813.9291   0.0000  0.0000  0.000000
2017-07-31  8222.1428   0.0000  0.0000  4.964809
2017-08-31  7010.1959   0.0000  0.0000  -17.288346
2017-09-30  5878.8063   0.0000  0.0000  -19.245227
.
.
.

df.iloc[:,0:3].plot.bar(figsize = size, ax = ax3)
df.iloc[:,-1].plot(figsize = size, ax = ax2)

图中只有一个图的另一个图(在ax1中)没有任何问题,因此我不会在此处发布。

问题是,当我运行此代码时,图中只有一个图(最后一行)保留,而另一个图则消失了。如果我切换最后两行的顺序,则其他图将保留。

任何想法为什么会这样?

编辑:我使用的是Jupyter笔记本,带有熊猫0.24和python 3.7

1 个答案:

答案 0 :(得分:1)

问题是

df.iloc[:,0:3].plot.bar(figsize = size, ax = ax3)

时将ax3.xticks设置为0, 1, ..., len(df)-1
df.iloc[:,-1].plot(figsize = size, ax = ax2)

使用df.index,在这种情况下(我想)使用时间戳,它是非常大的整数。这就是为什么您看不到两个地块之一的原因。建议重新绘制线条图:

df.iloc[:,0:3].plot.bar(figsize = size, ax = ax3)
ax2.plot(range(len(df)), df.iloc[:,-1])

您可以在我的答案here中尝试其他方法。