简体   繁体   English

how to remove empty space from bars for a specific group, that was plotted as seaborn bar plot on data in pandas dataframe

[英]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 Sec3USA 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.

相关问题 如何使用未绘制的 Dataframe 的列中的单独值(日期)注释 Seaborn 条 Plot - How to Annotate Seaborn Bar Plot with separate values (dates) from col of Dataframe which is not plotted Pandas DataFrame 条形图 - 从特定颜色图中绘制不同颜色的条形图 - Pandas DataFrame Bar Plot - Plot Bars Different Colors From Specific Colormap 如何在带有误差线的条形图中绘制熊猫数据框的特定行和列(基于行名和列名)? - How to plot specific rows and columns of pandas dataframe (based on name of row and name of column) in bar plot with error bars? 如何在 Python 中使用 pandas 和 matplotlib 绘制条形图时删除条形之间的空间? - How can I remove space between bars while plotting bar plot using pandas and matplotlib in Python? 从 matplotlib 条形图中删除空白空间 - Remove empty space from matplotlib bar plot 在 Pandas 条形图上使用来自 Dataframe 的值注释特定条形图 - Annotate specific bars with values from Dataframe on Pandas bar plots 使用 seaborn 深色主题并消除条形图中条形之间的间隙 - use seaborn dark theme and remove the gap between bars in a bar plot 在 matplotlib 中,绘制数据的组条 - In matplotlib, group bars of plotted data Dataframe 条 plot 与 Seaborn - Dataframe Bar plot with Seaborn 从数据框中绘制Seaborn中的百分比条 - plot percent bar in seaborn from dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM