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

问题描述

我有一个带有正负值的熊猫数据框,并希望将其绘制为条形图.

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).

我不知道如何通过 if >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.

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

08-11 16:15