1

I have data like this :

import pandas as pd
import matplotlib.pyplot as plt
index={'A','B','C','D','E'}
d={'typ':[1,2,2,2,1],'value':[10,25,15,17,13]}
df=pd.DataFrame(d,index=index)

I want to plot the dataframe in horizontal bars with different colors reffering to the column 'typ'

1
  • Perhaps the accepted answer to another matplotlib question may help you: it cycles through the individual bars (patches) and assigns a color to each patch individually. You'll need to adopt it for a barchart plot. Commented Jul 18, 2015 at 11:33

1 Answer 1

5

You can use the color parameter of matplotlib's barh function:

import pandas as pd
import matplotlib.pyplot as plt
index={'A','B','C','D','E'}
d={'typ':[1,2,2,2,1],'value':[10,25,15,17,13]}
df=pd.DataFrame(d,index=index)

# define the colors for each type
colors = {1:'blue', 2:'red'}

# plot the bars
plt.bar(range(len(df)), df['value'], align='center',
        color=[colors[t] for t in df['typ']])

The resulting figure

Sign up to request clarification or add additional context in comments.

Comments

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.