【问题标题】:Matplotlib bar chart with multiple columns and string X axis [duplicate]具有多列和字符串 X 轴的 Matplotlib 条形图 [重复]
【发布时间】:2020-09-01 09:09:20
【问题描述】:

我有两个平行的数据系列,我想为此制作一个包含多列的条形图。我理解这个想法是通过添加 x 轴的宽度来移动每一列,但是如果轴包含在字符串(分类变量)中呢?

假设这是一个熊猫数据框df

+----------+------+------+
| Category | Val1 | Val2 |
+----------+------+------+
| A        |    1 |    3 |
| B        |    4 |    6 |
| C        |    6 |    7 |
| D        |    3 |    9 |
+----------+------+------+

显然,这会引发错误:

import matplotlib.pyplot as plt
width = 0.4
fig, ax = plt.subplots()
ax.bar(x=df['Category'], height=df['Val1'], width=width)
ax.bar(x=df['Category']+width, height=df['Val2'], width=width)

您不能在字符串中添加数字。

那么,得到这样的东西的解决方案是什么:

【问题讨论】:

    标签: python pandas matplotlib bar-chart


    【解决方案1】:

    您可以使用pandas 绘图功能:

    fig, ax = plt.subplots()
    df.plot.bar(x='Category', ax=ax)
    

    输出:

    【讨论】:

    • 啊,是的!只是为了学习,如果有人可以在纯matplotlib中提出解决方案,我会非常感兴趣。
    • 对于纯 matplotlib,将条形移动+/- width/2
    • 我知道这就是想法,但你不能使用分类变量。您无法根据字符串计算班次。
    • 只针对np.arange(len(df))set_xticks
    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    相关资源
    最近更新 更多