按色调对条形图进行分类和排序

Categorize and order bar chart by Hue

我有问题。我想展示每个类别中排名最高的两个国家。但不幸的是,我只得到以下输出。但是,我希望将 part 列为一个额外的类别。 有选择吗?

import pandas as pd
import seaborn as sns
d = {'count': [50, 20, 30, 100, 3, 40, 5],
     'country': ['DE', 'CN', 'CN', 'BG', 'PL', 'BG', 'RU'],
     'part': ['b', 'b', 's', 's', 'b', 's', 's']
    }
df = pd.DataFrame(data=d)
print(df)

#print(df.sort_values('count', ascending=False).groupby('party').head(2))

ax = sns.barplot(x="country", y="count", hue='part',
                 data=df.sort_values('count', ascending=False).groupby('part').head(2), palette='GnBu')

我得到了什么

我想要的

以下方法为您的数据创建一个 FacetGrid。 Seaborn 11.2 引入了有用的 g.axes_dict。 (在示例数据中,我将 'BG' 的第二个条目更改为 'b',假设每个 country/part 组合只出现一次,如示例图中所示)。

from  matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

d = {'count': [50, 20, 30, 100, 3, 40, 5],
     'country': ['DE', 'CN', 'CN', 'BG', 'PL', 'BG', 'RU'],
     'part': ['b', 'b', 's', 's', 'b', 'b', 's']
     }
df = pd.DataFrame(data=d)
sns.set()
g = sns.FacetGrid(data=df, col='part', col_wrap=2, sharey=True, sharex=False)
for part, df_part in df.groupby('part'):
     order = df_part.nlargest(2, 'count')['country']
     ax = sns.barplot(data=df_part, x='country', y='count', order=order, palette='summer', ax=g.axes_dict[part])
     ax.set(xlabel=f'part = {part}')
g.set_ylabels('count')
plt.tight_layout()
plt.show()

你可以不使用seaborn,直接在matplotlib中绘制所有内容。

from  matplotlib import pyplot as plt
import pandas as pd

plt.style.use('seaborn')

df = pd.DataFrame({
    'count': [50, 20, 30, 100, 3, 40, 5],
    'country': ['DE', 'CN', 'CN', 'BG', 'PL', 'BG', 'RU'],
    'part': ['b', 'b', 's', 's', 'b', 'b', 's']
})

fig, ax = plt.subplots()
offset = .2
xticks, xlabels = [], []
handles, labels = [], []

for i, (idx, group) in enumerate(df.groupby('part')):
    plot_data = group.nlargest(2, 'count')
    x = [i - offset, i + offset]
    barcontainer = ax.bar(x=x, height=plot_data['count'], width=.35)
    
    xticks += x
    xlabels += plot_data['country'].tolist()
    handles.append(barcontainer[0])
    labels.append(idx)

ax.set_xticks(xticks)
ax.set_xticklabels(xlabels)
ax.legend(handles=handles, labels=labels, title='Part')
plt.show()