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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:48:12  来源:igfitidea点击:

Matplotlib Bar Chart choose color if value is positive vs value is negative

pythonmatplotlibpandas

提问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')

bar plot

条形图

回答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'}))

bar plot with positives green and negatives red

带正数绿色和负数红色的条形图

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>语法。

回答by Max Ghenis

If you want to avoid adding a column, you can do TomAugspurger's solution in one step:

如果你想避免添加一列,你可以一步完成TomAugspurger的解决方案:

data['values'].plot(kind='barh',
                    color=(data['values'] > 0).map({True: 'g',
                                                    False: 'r'}))

bar plot with positives green and negatives red

带正数绿色和负数红色的条形图

回答by user15964

Define

定义

def bar_color(df,color1,color2):
    return np.where(df.values>0,color1,color2).T

then

然后

data.plot.barh(color=bar_color(data,'r','g'))

gives

enter image description here

enter image description here

It also works for multiple bar series

它也适用于多个条形系列

df=pd.DataFrame(np.random.randint(-10,10,(4,6)))
df.plot.barh(color=bar_color(df,'r','g'))

gives

enter image description here

enter image description here