Matplotlib条形图选择颜色,如果值是正值而值是负数 [英] Matplotlib Bar Chart choose color if value is positive vs value is negative
问题描述
我有一个带有正负值的大熊猫DataFrame作为条形图.我想绘制正色绿色"和负值红色"(非常原始...大声笑).如果> 0绿色",否则我不知道如何通过< 0'红色'?
I have a pandas DataFrame with positive and negative values as a bar chart. I want to plot the positive colors 'green' and the negative values 'red' (very original...lol). I'm not sure how to pass if > 0 'green' else < 0 'red'?
data = pd.DataFrame([[-15], [10], [8], [-4.5]],
index=['a', 'b', 'c', 'd'],
columns=['values'])
data.plot(kind='barh')
推荐答案
我将为观察值是否大于0创建一个虚拟列.
I would create a dummy column for whether the observation is larger than 0.
In [39]: data['positive'] = data['values'] > 0
In [40]: data
Out[40]:
values positive
a -15.0 False
b 10.0 True
c 8.0 True
d -4.5 False
[4 rows x 2 columns]
In [41]: data['values'].plot(kind='barh',
color=data.positive.map({True: 'g', False: 'r'}))
此外,您可能要注意不要使列名与DataFrame属性重叠. DataFrame.values
给出DataFrame的基础numpy数组.名称重叠会阻止您使用df.<column name>
语法.
Also, you may want to be careful not to have column names that overlap with DataFrame attributes. DataFrame.values
give the underlying numpy array for a DataFrame. Having overlapping names prevents you from using the df.<column name>
syntax.
这篇关于Matplotlib条形图选择颜色,如果值是正值而值是负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!