Nick T
Nick T

Reputation: 683

How to plot grouped columns along the x-axis in Matplotlib?

I have a dataframe with three columns. City, State, and Sales.

To retrieve the total Sales for each city I use:

df.groupby(['City','State']).sum()[['Sales']]

Because I must be able to differenciate between cities of the same name, State needs to be included as well. Now, my question is, how can I group City and State along the x-axis and put Sales on the y-axis on a Matplotlib bar graph? I could just concatinate the City and State into its own column and then plot that new column on the x-axis. I find that somewhat sloppy though. What would the code look like to get the City and State together on the x-axis (without creating a new column). I want it to look something like the picture below. I appreciate the help. Thanks in advance.

enter image description here

Upvotes: 0

Views: 1091

Answers (2)

tdy
tdy

Reputation: 41327

Try this:

df.groupby(['City', 'State']).sum().plot.bar(xlabel='City', ylabel='Sales')

enter image description here

Upvotes: 1

Icarwiz
Icarwiz

Reputation: 194

Create a column name, with str, then groupby it, then plot, as simple as that...

df['Name'] = df['City'] + ' (' + df['State']) + ')'
df.groupby(['Name']).sum()[['Sales']].plot()

Upvotes: 0

Related Questions