【问题标题】:matplotlib double bar graph with pandas series带有熊猫系列的matplotlib双条形图
【发布时间】:2019-04-13 04:51:34
【问题描述】:

我有以下几点:

indyes = tuple(yesSeries.index)
indno = tuple(nodSeries.index)
width = 3

p1 = plt.bar(indyes, yesSeries, label="Example one", color='SkyBlue')
p2 = plt.bar(indno, nodSeries, label="Example two", color='IndianRed')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')

plt.title('Epic Graph\nAnother Line! Whoa')

plt.show()

它将我的图表绘制为堆积条形图:

当我尝试将 + width 添加到第二个条形图 indno + width 时,它们不会堆叠,而是并排出现以下错误:TypeError: can only concatenate tuple (not "int") to tuple

我已将我的 Pandas 系列设置为一个元组以提取日期和计数信息。

如何获得两个平行的垂直条形图?

【问题讨论】:

  • 在这里使用tuple 的原因是什么?要添加3 days to each item in the index吗?
  • @ ImportanceOfBeingErnest 我的数据框按时间戳分组,我的最终数据集是带有时间戳和计数的 pandas.core.series.Series。我正在使用元组来访问我的情节中我的 x 和 y 值的系列中的时间戳和计数。情节似乎运作良好,我更喜欢 2 个条而不是堆叠条。
  • 不确定这是否能回答我的问题。无论如何,您也可以决定在这里提供minimal reproducible example,这样人们就可以简单地提供答案而无需了解其动机。
  • @ImportanceOfBeingErnest 不,我不想增加 3 天。我想要 2 个水平条形图,而不是堆叠条形图。
  • 水平条形图是通过barh创建的。

标签: pandas matplotlib tuples bar-chart


【解决方案1】:

我相信您可以从您的Series 创建一个DataFrame,然后使用plot.bar 函数来完成您要查找的内容。

在下面的代码中,我生成数据并根据需要创建图表。

import matplotlib.pyplot as plt
import pandas as pd
times = pd.date_range('2018-09-01', periods=7, freq='5D')
yesSeries = pd.Series([1800,2000,3000,1000,2000,1500,1700], index=times)
nodSeries = pd.Series([200,500,700,600,300,50,0], index=times)

df = pd.DataFrame({"Example one":yesSeries,"Example two":nodSeries})
ax = df.plot.bar(color=["SkyBlue","IndianRed"], rot=0, title="Epic Graph\nAnother Line! Whoa")
ax.set_xlabel("date")
ax.set_ylabel("counts")
ax.xaxis.set_major_formatter(plt.FixedFormatter(times.strftime("%b %d %Y")))
plt.show()

结果如下图。

如果日期看起来很混乱,您可以在plt.show() 代码之前插入以下行:

plt.gcf().autofmt_xdate()

这将导致下图。

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 2020-08-31
    • 2021-03-28
    • 2019-04-30
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多