如何使用列表理解来设置颜色?

时间:2017-11-08 01:21:48

标签: python pandas matplotlib plot list-comprehension

考虑以下条形图。 enter image description here

为了让条形高于40000的蓝色和低于40000的红色条形,我尝试使用以下列表理解:

df.count().plot(kind = 'bar', color = ['powderblue' if df[e].count() > 40000 else 'red' for e in df])
  • df是我的数据框
  • df[e].count()应返回每列中包含的非NaN值的数量

然而,matplotlib会返回: enter image description here

......全是红色。

更奇怪的是,同样的列表理解在单独使用时非常有效:

colors = ['powderblue' if df[e].count() > 40000 else 'red' for e in df]
Print(colors)

powderblue
powderblue
powderblue
powderblue
powderblue
powderblue
powderblue
powderblue
red
...

有人可以解释一下我在这里缺少的东西吗?

编辑:数据框如下所示:

    code    url   creator  quantity   brands
1     3     NaN      B       0.5        Ta  
2     NaN   Se       A       3.8        De 
3     6     Th       D       6.8        NaN
4     2     Fr       C       NaN        Be 
5     1     Il       F       2.4        Pm
...

MCVE:

# creating an array of shape 10x10
array = np.random.choice(10, size = (10, 10))

# transforming it in a dataframe and replacing zeros and ones by NaN
df = pd.DataFrame(array).replace((0,1), np.nan)
print(df)

    0   1   2   3   4   5   6   7   8   9
0   8.0     NaN     6   5   8.0     NaN     NaN     2.0     NaN     7.0
1   7.0     8.0     7   8   9.0     8.0     9.0     8.0     8.0     5.0
2   9.0     8.0     7   7   6.0     8.0     8.0     7.0     8.0     6.0
3   4.0     4.0     3   3   3.0     5.0     4.0     2.0     6.0     4.0
4   5.0     7.0     4   9   2.0     8.0     NaN     7.0     NaN     5.0
5   7.0     6.0     6   7   NaN     5.0     NaN     5.0     4.0     3.0
6   6.0     8.0     5   5   4.0     NaN     3.0     NaN     9.0     2.0
7   9.0     5.0     4   3   NaN     7.0     6.0     4.0     8.0     NaN
8   NaN     2.0     8   8   7.0     7.0     2.0     9.0     3.0     5.0
9   3.0     9.0     6   3   9.0     NaN     9.0     7.0     2.0     8.0

# creating a working list comprehension
colors = ['blue' if df[e].count() > 8 else 'red' for e in df]
print(colors)

'blue', 'blue', 'blue', 'blue', 'red', 'red', 'red', 'blue', 'red', 'blue'

# plotting the dataframe using the same list comprehension
df.count().plot(kind = 'bar', color = colors)

enter image description here

1 个答案:

答案 0 :(得分:0)

我使用的matplotlib版本(2.0.2)已过时,并以某种方式阻止列表理解正确运行。 2.1.0版解决了这个问题。

感谢DavidG的建议。

the list comprehension works perfectly fine with the lastest version of matplotlib (2.1.0)