Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 458
user3055920 Avatar asked Mar 10 '14 20:03

user3055920


People also ask

Can you use the same Colour for the data bars of negative and positive values?

When you create a chart in Excel using positive and negative values, both positive and negative graphs are the same color by default. Another way to display the chart is to change the color of the negative values; this is especially appealing in cases where negative values need to be emphasized to viewers.

How do you separate colors for positive and negative bars in a column bar chart?

1. If you have Excel 2013, choose the Format Data Series from the right click menu to open the Format Data Series pane, and then click Fill & Line icon, and check Invert if negative option, then check Solid fill and specify the colors for the positive and negative data bar as you want beside Color section.

How do you change the color of a bar graph based on value?

Select the bar chart or column chart, then click Kutools > Charts > Color Chart by Value. Then in the popped-out dialog, set the value range and the relative color as you need. Click to free download now!


1 Answers

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.

like image 194
TomAugspurger Avatar answered Sep 29 '22 11:09

TomAugspurger