Matplotlib different colors for bar graph based on value

10,969

Solution 1

After few tries with Pandas plot() I didn't find a way to achieve what you expect but you can easily do that with Matplotlib directly.

I hope this will help:

I created sample df:

df = pd.DataFrame({'a' : [2,6,2,4,5,3,7]})

and I create two temp df which will store only values satisfying the condition:

t1 = df[df['a']<5]
t2 = df[df['a']>=5]

and then just plot it :

plt.bar(t1.index.values, t1['a'], color='r')
plt.bar(t2.index.values, t2['a'], color='g')

the final result looks like this:

enter image description here

Is that what you expect?

Solution 2

You can achieve your result in a single call to plt.bar this way:

df = pd.DataFrame({'a' : [2,6,2,4,5,3,7]})
df['colors'] = 'r'
df.loc[df.a>=5,'colors'] = 'g'
plt.bar(df.index, df.a, color=df.colors)

You also mention in a comment that sectordict[i] is a dictionary, but you can easily convert a dictionary into a dataframe with: pd.DataFrame.from_dict.

Share:
10,969
thomas.mac
Author by

thomas.mac

Updated on June 25, 2022

Comments

  • thomas.mac
    thomas.mac about 2 years

    I'm plotting returns for sectors and all the stocks in them. I would like to have the values > 100 to be green, and < 100 to be red. Here's my code:

    sector_lst = ['XLK','XLF','XLE']  ## etc.
    
    for i in sector_lst:                   
        fig = plt.figure(figsize=(12, 8)) 
    
        for x in sectordict[i]:                #sectordict[i] is all the stocks in a sector (so AAPL, GOOG, etc. for tech) 
            if pct_change[x] > 1:              
                 pct_change[sectordict[i]].plot(kind='bar',color='g') 
    
            ##if pct_chg < 1
            else:                              
                 pct_change[sectordict[i]].plot(kind='bar',color='r') 
    
    
    plt.title(i)
    

    So far this is returning the whole sector graphs as green or red; if the first value is > 100 all stocks will be green and vice versa.

    My expected output is to have 11 graphs (which it currently does), but with different colors for each stock within the graph, if stock had > 100% return then it shows green and < 100% it shows red.

  • thomas.mac
    thomas.mac almost 7 years
    this is what I want the graph to look like, but my sectordict[i] isn't a df, but rather a dictionary
  • Kacper Wolkowski
    Kacper Wolkowski almost 7 years
    If you will add some sample data I could help more, and customize this plots to your example.