Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

python - Bar Chart: How to choose color if value is positive vs value is negative

I have a pandas dataframe with positive and negative values and want to plot it 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')

bar plot

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.values give the underlying numpy array for a DataFrame. Having overlapping names prevents you from using the df.<column name> syntax.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...