Chetan
Chetan

Reputation: 31

I need to plot grouped data using matplotlib or seaborn

I am trying to plot countries departments and their sales. So i have country, departments and their sales numbers in diff columns. And i need to create bar plot, so it should look like country1 and its departments on x-axis and sales y-axis, then country2 and so-on.

I tried seaborn's catplot but its giving me a diff plot for each country, using plotly's bar its just plotting all the departments together. I need it to be grouped based on the countries.

Any input is appreciated. Thanks

Upvotes: 2

Views: 409

Answers (1)

JohanC
JohanC

Reputation: 80329

You could create a barplot() using 'Country' as x and 'Department' as hue:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns

df = pd.DataFrame({'Country': np.repeat(['Albania', 'Botswana', 'Chili'], 4),
                   'Department': np.tile(['Department1', 'Department2', 'Department3', 'Department4'], 3),
                   'Sales': np.random.randint(10000, 100000, 12)})
sns.barplot(data=df, x='Country', y='Sales', hue='Department')
plt.show()

example plot

An approach to cope with empty bars, is to create stacked bars:

df.pivot(index='Country', columns='Department').plot(kind='bar', stacked=True, rot=0)

stacked bars example

Upvotes: 1

Related Questions