【问题标题】:Pandas - Bar and Line Chart - Datetime axisPandas - 条形图和折线图 - 日期时间轴
【发布时间】:2019-06-25 23:31:53
【问题描述】:

我正在尝试绘制条形图和线叠加图,其中我的数据将日期时间作为索引。 这是代码:

import pandas as pd
import numpy as np
dates = pd.date_range('2019-01-01', '2019-01-31', freq='B')
df = pd.DataFrame(index=dates, 
              columns=['a', 'b', 'c'],
              data = np.random.randn(len(dates), 3))

fig, ax = plt.subplots()
df.plot.bar(ax=ax)
df.sum(axis=1).plot(ax=ax)

不幸的是,它只显示最后一个请求的图表。

我正在使用

python 3.6.8
pandas 0.24.0
matplotlib 3.0.2

问候

【问题讨论】:

  • 你用在笔记本上吗?
  • 对我来说,它只显示 matplotlib 2.2.2 上的第一张图(条形图)
  • 根据评论here 它与索引有关。如果我在两个绘图命令中都设置了use_index=False,那么条形图和线形图都是可见的,但是 xticks 只是从 0 到 22 的数字。
  • Pandas 条形图本质上是分类的,它们将条形图作为连续的整数位置。因此,要在同一轴上绘制线图,线图也需要是分类的。这可以通过上面评论的use_index=False 来实现。所以解决办法就是把最后一行换成df.sum(axis=1).plot(ax=ax, use_index=False)
  • 我相信处理这个问题的最熊猫式的方法是使用use_index=False的@ImportanceOfBeingErnest 提示

标签: python python-3.x pandas matplotlib


【解决方案1】:

你可以这样做:

fig = plt.figure()
ax = df.plot.bar()
ax2 = ax.twinx()
ax2.plot(df.sum(axis=1).values)
plt.show()

df.plot.bar 返回一个可用于下一个绘图的轴:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html#pandas-dataframe-plot

还讨论过:

How to align the bar and line in matplotlib two y-axes chart?

Plot Pandas DataFrame as Bar and Line on the same one chart

【讨论】:

    【解决方案2】:

    在@ImportanceOfBeingErnest 发表评论之后,我认为回答这个问题的最佳方法是使用use_index=False kwarg。 对于数据格式等,这是另一个问题,取决于人们想要实现的目标。

    import pandas as pd
    import numpy as np
    dates = pd.date_range('2019-01-01', '2019-01-31', freq='B')
    df = pd.DataFrame(index=dates,
                      columns=['a', 'b', 'c'],
                      data = np.random.randn(len(dates), 3))
    
    fig, ax = plt.subplots()
    df.plot.bar(ax=ax)
    df.sum(axis=1).plot(ax=ax, use_index=False)
    

    【讨论】:

    • 我发誓我以为这个人像是一台笔记本电脑;)
    • 如果您对此解决方案感到满意,请考虑接受它(即使这是您自己的答案),以便其他人知道该问题不需要进一步关注。
    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 2018-09-20
    相关资源
    最近更新 更多