0

I'm doing an horizontal barplot. I need one specific bar (type=milk) to have a green fill color, and gray for the other types. The dataframe is:

df = DataFrame(val  = c(1, 2, 3, 6, 7, 8),
                type = c("honey","bread","coffee","bread","honey","milk"))

I have tried this without success:

clrs = ['green' if ((x == milk) else 'gray' for x in type]
ax.barh(df['type'], (df['val']), align='center', colors=clrs)

Any ideas?

1 Answer 1

1

Yes, you could change the patch of the appropriate bar, something like

b=ax.barh(df['type'], (df['val']), align='center', colors=clrs)

b.patches[4].set_color('green')

However I don't understand why you are repeating the same labels multiple times.

If you didn't have repeated elements you could find the label milk automatically like this:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
df = pd.DataFrame({'val': np.array([1, 2, 3, 6]), 'types': ["honey", "coffee", "bread","milk"]})

b = plt.barh(df['types'], df['val'], align='center', color='gray')
index_milk = df[df['types']=='milk'].index[0]
b.patches[index_milk].set_color('green')
plt.show()
Sign up to request clarification or add additional context in comments.

5 Comments

Some labels repeat since in the full dataframe, some of them do. Just trying to better reproduce the issue.
if labels repeat you will have a problem that does not relate to the color. My answer should solve the color problem though, right?
could you accept it if it solved your problem? If it didn't, could you say why it didn't? Thanks
Hi Vaaal88. One last question. Let's say I have 500 labels in my dataframe and some of them repeat, is there a way to use b.patches and the name of the label? Something like b.patches[df('milk')]. Thank you.
the problem is that, in pandas, when a label repeats, only the last one is plotted, so there will be an object 'patches' only for the last bar. That's why I told you it's a problem to have repeated elements. Conceptually, what does it mean? Bread has a value of 2 and a value of 6? Maybe if you clarify this point I can help you out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.