【问题标题】:Python Pandas Bar Chart - change color for specific barsPython Pandas 条形图 - 更改特定条形的颜色
【发布时间】:2020-02-05 13:12:11
【问题描述】:

我在 csv 中有一些数据。

它只有一列和内容字符串,足球比分如“0:0”、“1:2”等。

然后我用df[0].value_counts().plot(kind='bar') 构建直方图。

仅对具有“绘制”分数(0:0、1:1、...)的条形更改颜色的最佳方法是什么?

我可以添加第二列,'1' 用于平局,'0' 用于其他,但不明白如何将其用作条形颜色。

我在这里尝试了另一个问题的解决方案

df[0].value_counts().plot(kind='bar', color=(df[1] == 1).map({True: 'orange', False: 'blue'})) 但颜色错误

wrong coloring,期待橙色“1:1”
示例数据框:

      0  1
0   2:0  0
1   2:3  0
2   1:1  1
3   1:3  0
4   2:0  0
5   3:4  0
6   1:2  0
7   0:1  0
8   2:3  0
9   0:1  0
10  1:1  1
11  2:1  0
12  0:1  0
13  1:2  0
14  0:3  0

【问题讨论】:

    标签: python pandas matplotlib bar-chart


    【解决方案1】:

    使用numpy.where 测试1 列是否匹配Index.isin 用于传递给color 参数的颜色数组:

    a = df[0].value_counts()
    colors = np.where(a.index.isin(df.loc[df[1] == 1, 0].unique()), 'orange', 'blue')
    a.plot(kind='bar', color=colors)
    

    【讨论】:

    • 谢谢,它有效!有没有办法在没有 numpy 的情况下做到这一点?
    • 如果使用 panas,也使用 numpy,所以如果使用 pd.np.where 而不是 np.where 它可以工作
    • @dad 或使用colors = a.index.isin(df.loc[df[1] == 1, 0].unique()).map({True: 'orange', False: 'blue'})
    • @dad 或使用 colors = a.index.isin(df.loc[df[1] == 1, 0].unique()).to_series().map({True: 'orange', False: 'blue'}) 如果熊猫版本较旧
    猜你喜欢
    • 2012-10-18
    • 2018-02-08
    • 2014-04-07
    • 2011-08-03
    • 2012-01-19
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多