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

前端 未结 4 2085
[愿得一人]
[愿得一人] 2020-11-28 11:02

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

4条回答
  •  醉梦人生
    2020-11-28 11:52

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

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

提交回复
热议问题