Python 如何使用列表设置颜色?
考虑以下条形图。 为了将高于40000的条涂成蓝色,将低于40000的条涂成红色,我尝试使用以下列表:Python 如何使用列表设置颜色?,python,pandas,matplotlib,plot,list-comprehension,Python,Pandas,Matplotlib,Plot,List Comprehension,考虑以下条形图。 为了将高于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会返回以下内容: 。。。全红了 更奇怪的是,同样的列表理解在单独使用时
df.count().plot(kind = 'bar', color = ['powderblue' if df[e].count() > 40000 else 'red' for e in df])
是我的数据帧df
应返回每列中包含的非NaN值的数量df[e].count()
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:
我使用的matplotlib版本(2.0.2)已经过时,并且不知何故阻止了列表理解的正确运行。版本2.1.0解决了这个问题
谢谢大卫的建议
我使用的matplotlib版本(2.0.2)已经过时,并且不知何故阻止了列表理解的正确运行。版本2.1.0解决了这个问题
谢谢大卫的建议
你能举个例子说明你的数据框是什么样子吗?当然,我刚刚编辑了我的问题。你能试着找一个吗?我刚刚用你粘贴的数据框尝试了你的代码,使用的是
df.count().plot(kind='bar',color=['powderblue'如果df[e].count()>4,否则df中的e为'red')
而不是40000,得到了四个红色和一个蓝色的“creator”,正如预期的那样。谢谢@DSM。我刚刚用mcve更新了这个问题。你的代码对我有用。您使用的matplotlib和pandas的版本是什么?您能举例说明您的数据框是什么样子吗?当然,我刚刚编辑了我的问题。您能试着找到一个吗?我刚刚用你粘贴的数据框尝试了你的代码,使用的是df.count().plot(kind='bar',color=['powderblue'如果df[e].count()>4,否则df中的e为'red')
而不是40000,得到了四个红色和一个蓝色的“creator”,正如预期的那样。谢谢@DSM。我刚刚用mcve更新了这个问题。你的代码对我有用。您使用的matplotlib和pandas版本是什么?
# 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)