How To Remove Empty Space From Bars For A Specific Group, That Was Plotted As Seaborn Bar Plot On Data In Pandas Dataframe
I have a dataset which looks like this: import pandas as pd, seaborn as sns, matplotlib.pyplot as plt, numpy as np data = {'country': ['USA', 'USA', 'USA', 'GBR', 'GBR', 'GBR
Solution 1:
This happens because you've got missing values in your DataFrame.
You can clearly see them pivoting the df
pivot = df.pivot(index=['country'], columns=['sector'], values='counts_log')
print(pivot)
that gives
sector Others Sec1 Sec2 Sec3
country
GBR 2.7634282.6627582.682145NaN
IND 2.5211382.285557NaN2.187521
USA 3.9426533.9096103.893318NaN
So, there is "space" in IND
Sec2
because you have no data. Same for GBR
Sec3
and USA
Sec3
.
The only workaround I can suggest is to plot in subplots like
color_map = {
'Others': 'C0',
'Sec1': 'C1',
'Sec2': 'C2',
'Sec3': 'C3',
}
df['color'] = df.sector.map(color_map)
fig, ax = plt.subplots(1, 3, figsize=(15, 5), sharey=True)
for i, country inenumerate(df.country.unique()):
_df = df[df.country==country].sort_values(by='sector')
sns.barplot(
ax=ax[i],
data=_df,
x='sector', y='counts_log',
palette=_df.color
)
ax[i].set(
title=country
)
Maybe this is not exactly what you were searching for but hope it can help.
Post a Comment for "How To Remove Empty Space From Bars For A Specific Group, That Was Plotted As Seaborn Bar Plot On Data In Pandas Dataframe"