1

There are a few things that I would like to express in a bar chart and have no clue about doing it using basic graphing techniques in matplotlib. I have a dataframe which is shown below and would like to obtain a bar chart as described below. The x-axis is based on the the Type column of the dataframe and within a single bar, the different colors are based on the Name column and the size of the bar is defined by the Count number. The color of the different names need not to be the same across different types, as long as the colors within a single bar is different.Example of the given dataframe Bar chart

2 Answers 2

2

You can use pivot and then plot

df.pivot('Type', 'Name', 'Count').plot(kind = 'bar', stacked = True,  color = ['b','g','orange','m', 'r'])

Edit: To sort the values

df.pivot('Type', 'Name', 'Count').sort_values(by = 'A', ascending = False, axis = 1)\
.plot(kind = 'bar', stacked = True, color = ['g','r','b','orange', 'm'])

enter image description here

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

3 Comments

Is there a way to sort the bar chart in descending order of the counts?
I think I know how. I can create an extra column called 'Sum' which is the sum of the other columns and sort based on that before plotting it. Thanks a lot for your help! This works great :)
See the edit for sort and thank you for accepting :)
0

I you want to change the size of plot the use arg figsize=(15, 5)

df.pivot('Type', 'Name', 'Count').sort_values(by = 'A', ascending = False, axis = 1)\
.plot(kind = 'bar', stacked = True, color = ['g','r','b','orange', 'm'], figsize=(15,5))

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.