【问题标题】:Coloring bars with different colors 'manually' or using a logical expression in pandas barplot使用不同颜色的着色条“手动”或在 pandas barplot 中使用逻辑表达式
【发布时间】:2018-12-06 17:54:28
【问题描述】:

我想用颜色条来表示超过数值的值,并且这些值与时间序列中的特定年份间隔相关,颜色与其他颜色不同。

我第一次尝试“手动”进行 - 即通过手动为图中的每个条形指定颜色 - 导致异常。我想知道如何更正代码,以及是否有办法使用逻辑表达式自动着色。

我的数据是:

df1

2004    23
2005    10
2006     2
2007    15
2008    13
2009    15
2010    30
2011    38
2012    42
2013    72

my_colors = 'b'*6 + 'r'*4
my_colors # I want bars representing values above 15 and after 2005 to be colored 
          # red, while the rest blue
'bbbbbbrrrr' 
df1.plot(kind = 'bar', color = my_colors, figsize = (10, 8))
plt.title('Immigration from Iceland to Canada')
plt.xlabel('Year')
plt.ylabel('Number of Immigrants')
plt.show()

ValueError: Invalid RGBA argument: 'bbbbbbrrrr'

【问题讨论】:

    标签: python-3.x pandas matplotlib colors bar-chart


    【解决方案1】:

    假设您有一个名为 包含这些数值的值和这些日期的日期

    a = (df['Value'] > 15)& (df['Date'] > 2005)
    
    colors = np.where(a, 'r', 'b')
    print(colors)
    
    ['b' 'b' 'b' 'b' 'b' 'b' 'r' 'r' 'r' 'r']
    

    现在你可以在你的情节中使用这种颜色

    color = colors
    

    【讨论】:

      猜你喜欢
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 2020-05-30
      相关资源
      最近更新 更多