【问题标题】:Pyplot stacked bars with dates带有日期的 Pyplot 堆积条形图
【发布时间】:2022-01-20 07:25:47
【问题描述】:

首先 - 抱歉这个问题太笼统了,但我没有找到我正在寻找的代码的好例子。

我的 DF 类似于:

Customer Size Date
Customer1 5 01.01.2021
Customer2 2 01.01.2021
Customer3 6 01.01.2021
Customer1 5 02.01.2021
Customer2 4 02.01.2021
Customer3 5 02.01.2021

基本上,我有一些客户每天使用特定数量的存储空间。 我需要一个堆积条形图,其中每个条形图是一天,每个条形图的部分是客户。我计划将 30 天的历史记录放在一个图表中,这意味着 30 个柱及其 X 个部分。

条形之间不需要有视觉空间。

谢谢!

【问题讨论】:

  • 首先运行df['Date'] = pd.to_datetime(df['Date'])。那就试试df.pivot(index='Date', columns='Customer', values='Size').plot(kind='bar', stacked=True)
  • 谢谢。我收到 ValueError: Index contains duplicate entries, cannot reshape 日期列有重复是正常的,因为 DF 包含来自同一日期的多个客户的数据。
  • 日期和客户的值必须重复。尝试df[df.duplicated(subset=['Date', 'Customer'], keep=False)] 检查是否是这种情况。尝试对这两个字段进行重复数据删除或聚合以修复数据。
  • 是的。我发现了我的问题。现在一切正常!

标签: python pandas matplotlib


【解决方案1】:

按照@ChrisAdams 的建议在绘图之前转换您的数据框

out = df.pivot('Date', 'Customer', 'Size')
print(out)

# Output:
Customer    Customer1  Customer2  Customer3
Date                                       
01.01.2021          5          2          6
02.01.2021          5          4          5

现在您可以绘制数据框了:

out.plot.bar(stacked=True, rot=0)
plt.show()

更新

我问这个,因为我想更改图形参数,并且找不到将您的语法与 fig, ax=... 方式结合起来的方法。

fig, ax = plt.subplots()
out.plot.bar(stacked=True, rot=0, ax=ax)

【讨论】:

  • 尝试你的例子我也收到了同样的错误 - 索引包含重复的条目,无法重塑
  • 我发现了问题。一切正常!
  • 最后一个问题 - 如何将out.plot.bar(stacked=True, rot=0) 转换为plt.bar(out,stacked=True, rot=0) 之类的东西
  • 这样做并非易事,因为您必须手动进行。检查matplotlib.org/stable/gallery/lines_bars_and_markers/…
  • 好的。我明白了。我更新了我的答案。你还好吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 2016-03-11
相关资源
最近更新 更多