Home > Software design >  python - On my horizontal bar plot how do I assign specific color to certain index
python - On my horizontal bar plot how do I assign specific color to certain index

Time:02-13

this is my simplified code

import numpy as np
import pandas as pd
pd.DataFrame(np.random.randint(1,100,6),index=['1200 am', '1230 am', '0340 pm', '1200 pm', '1030 am', '0140 pm'],columns=['value']).plot(kind='barh')

enter image description here

I want bars for "am" colored in red to distinguish between "am" and "pm", how do I do that?

CodePudding user response:

You can plot your data in two passes using a mask like so:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(1,100,6), 
             index=['1200 am', '1230 am', '0340 pm', '1200 pm', '1030 am', '0140 pm'],
             columns=['value'])

m = df.index.str.contains('am')
ax = df.value.mask(m).plot(kind='barh')
df.value.mask(~m).plot(kind='barh', color='r', ax=ax)

enter image description here

  • Related