aviss
aviss

Reputation: 2439

Change colour of bars based on string value

I have a data frame with weekdays. I need to highlight weekends ('Saturday' & 'Sunday') with a different color on my bar chart. I found some solutions where I can set a different color by index.get_indexer. But how can I do it more efficiently by setting a condition? Will appreciate your help!

# create an example of my df
dates = pd.DataFrame({'dates': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday',
                               'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
                   'stats':[10,20,30,40,50,60,70,10,20,30,40,50,60,70],
                   'other':[44,55,66,88,33,22,11,44,55,66,88,33,22,11]})

# And plot it...
ax = dates.plot(x='dates', y='stats', kind='bar', color='b')

    ax.patches[dates.index.get_indexer([5])[0]].set_facecolor('orange')
    ax.patches[dates.index.get_indexer([6])[0]].set_facecolor('orange')
# etc...

    ax.legend()
    plt.show()

Upvotes: 0

Views: 436

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339240

You may loop over the dataframe and set those patches matching "Saturday" or "Sunday" to orange.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create an example of my df
dates = pd.DataFrame({'dates': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday',
                               'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
                   'stats':[10,20,30,40,50,60,70,10,20,30,40,50,60,70],
                   'other':[44,55,66,88,33,22,11,44,55,66,88,33,22,11]})

ax = dates.plot(x='dates', y='stats', kind='bar', color='b')

weekend = (dates['dates']=='Sunday') | (dates['dates']=='Saturday')
for i,b in enumerate(weekend):
    if b:
        ax.patches[i].set_facecolor('orange')

ax.legend()
plt.show()

Not sure if this is the most efficient way.

Upvotes: 1

Related Questions