【问题标题】:Plotting barplot and line from pandas dataframe with different y axis从具有不同 y 轴的 pandas 数据框中绘制条形图和线条
【发布时间】:2019-05-16 23:18:58
【问题描述】:

我有以下要绘制的数据框。我试图有 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 notebook,带有 pandas 0.24 和 python 3.7

【问题讨论】:

  • 我不明白这个问题。这对我来说可以。最后一个图是正确的:有一个条形图和一条线。你还有什么期待? col2 为零,因此您看不到 col2 的任何条形。唯一的酒吧将来自col1
  • 我的问题是我要么看到条形图,要么看到线条,但不能同时看到两者。我正在使用一个 jupyter notebook,最后一个版本的 pandas 和 python 3.7
  • 奇怪。它在 3.6.5 python、pandas 0.23.0 中对我来说很好用
  • 尝试以下操作:df.iloc[:,0:3].plot.bar(ax=ax2, secondary_y=True) 然后df.iloc[:,-1].plot(ax=ax2)
  • 你的数据框是否被Date索引?

标签: python pandas matplotlib


【解决方案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中尝试一些其他方法。

【讨论】:

    猜你喜欢
    • 2015-09-01
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多