[英]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", "IND", "IND", "IND"],
"sector": ["Others", "Sec1", "Sec2", "Others", "Sec2", "Sec1", "Others", "Sec1", "Sec3"],
"counts": [8763, 8121, 7822, 580, 481, 460, 332, 193, 154]}
df = pd.DataFrame.from_dict(data)
df['counts_log'] = df['counts'].apply(lambda x: np.log10(x))
When I am plotting this data using the following code:当我使用以下代码绘制此数据时:
plt.figure(figsize=(18, 6))
sns.barplot(x='country', y='counts_log', hue='sector', data=df, palette='tab10')
plt.legend([],[], frameon=False)
plt.show()
I get the following issue (there is always some space between the bars of IND):我遇到以下问题(IND 的条之间总是有一些空间):
Whatever I had tried, it is not going away.无论我尝试过什么,它都不会消失。 How to fix the issue?
如何解决问题?
This happens because you've got missing values in your DataFrame.发生这种情况是因为您的 DataFrame 中缺少值。
You can clearly see them pivoting the df你可以清楚地看到他们旋转 df
pivot = df.pivot(index=['country'], columns=['sector'], values='counts_log')
print(pivot)
that gives这给了
sector Others Sec1 Sec2 Sec3
country
GBR 2.763428 2.662758 2.682145 NaN
IND 2.521138 2.285557 NaN 2.187521
USA 3.942653 3.909610 3.893318 NaN
So, there is "space" in IND
Sec2
because you have no data.因此,
IND
Sec2
中有“空间”,因为您没有数据。 Same for GBR
Sec3
and USA
Sec3
. GBR
Sec3
和USA
Sec3
。
The only workaround I can suggest is to plot in subplots like我可以建议的唯一解决方法是 plot 在子图中
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 in enumerate(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.也许这不是您正在寻找的东西,但希望它可以提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.