条形图:如果值为正值与值为负值如何选择颜色 [英] Bar Chart: How to choose color if value is positive vs value is negative

查看:35
本文介绍了条形图:如果值为正值与值为负值如何选择颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含正值和负值的 Pandas 数据框,想将其绘制为条形图.

I have a pandas dataframe with positive and negative values and want to plot it as a bar chart.

我想绘制正值绿色"和负值红色"(非常原始...lol).

I want to plot the positive colors 'green' and the negative values 'red' (very original...lol).

如果 > 我不知道如何通过0 '绿色' 其他 <0 '红色'?

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

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.

这篇关于条形图:如果值为正值与值为负值如何选择颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆