``手动''使用不同颜色的彩条或在熊猫条图中使用逻辑表达式

时间:2018-06-27 18:42:59

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

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

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

我的数据是:

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'

1 个答案:

答案 0 :(得分:0)

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

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