![](/img/trans.png)
[英]How to Annotate Seaborn Bar Plot with separate values (dates) from col of Dataframe which is not plotted
[英]how to remove empty space from bars for a specific group, that was plotted as seaborn bar plot on data in pandas dataframe
我有一個如下所示的數據集:
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))
當我使用以下代碼繪制此數據時:
plt.figure(figsize=(18, 6))
sns.barplot(x='country', y='counts_log', hue='sector', data=df, palette='tab10')
plt.legend([],[], frameon=False)
plt.show()
我遇到以下問題(IND 的條之間總是有一些空間):
無論我嘗試過什么,它都不會消失。 如何解決問題?
發生這種情況是因為您的 DataFrame 中缺少值。
你可以清楚地看到他們旋轉 df
pivot = df.pivot(index=['country'], columns=['sector'], values='counts_log')
print(pivot)
這給了
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
因此, IND
Sec2
中有“空間”,因為您沒有數據。 GBR
Sec3
和USA
Sec3
。
我可以建議的唯一解決方法是 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
)
也許這不是您正在尋找的東西,但希望它可以提供幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.