pandas Matplotlib 条形图选择颜色,如果值是正值 vs 值是负值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/22311139/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib Bar Chart choose color if value is positive vs value is negative
提问by user3055920
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'?
我有一个带有正值和负值的 Pandas DataFrame 作为条形图。我想绘制正颜色“绿色”和负值“红色”(非常原始......大声笑)。如果 > 0 'green' else < 0 'red',我不确定如何通过?
data = pd.DataFrame([[-15], [10], [8], [-4.5]],
                    index=['a', 'b', 'c', 'd'],
                    columns=['values'])
data.plot(kind='barh')
回答by TomAugspurger
I would create a dummy column for whether the observation is larger than 0.
我会为观察值是否大于 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'}))
Also, you may want to be careful not to have column names that overlap with DataFrame attributes. DataFrame.valuesgive the underlying numpy array for a DataFrame. Having overlapping names prevents you from using the df.<column name>syntax.
此外,您可能需要注意不要让列名与 DataFrame 属性重叠。DataFrame.values给出 DataFrame 的底层 numpy 数组。名称重叠可防止您使用该df.<column name>语法。


