带组序的 Seaborn 计数图

Seaborn countplot with group order

我尝试使用 seaborn 和 matplotlib 绘制计数图。鉴于每年,我想对每年的“干旱类型”计数进行排序,以使其看起来更好。目前它每年都没有分类,看起来很乱。 谢谢!

import seaborn as sns
import matplotlib.pyplot as plt
count=pd.read_csv(r"https://raw.githubusercontent.com/tuyenhavan/Course_Data/main/count.csv")

plt.figure(figsize=(15,8))
sns.countplot(x= 'Year', hue = 'Drought types', data = count, palette = 'YlOrRd')

plt.legend(loc = "best",frameon=True,bbox_to_anchor=(0.9,0.75))
plt.show()

以下方法绘制年份 one-by-one。 order=用于固定年份的顺序。 hue_order 为每一年重新计算(需要 .reindex() 以确保所有 drought_types 都存在)。

字典调色板用于确保每个色调值获得相同的颜色,与顺序无关。自动图例会重复每年的所有色调值,因此需要减少图例。

顺便说一句,loc='best' 不应与图例中的 bbox_to_anchor 一起使用,因为它可能会导致非常意外的数据变化很小。 loc='best' 将更改为 9 个可能的位置之一,具体取决于可用的 space。

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

count = pd.read_csv("https://raw.githubusercontent.com/tuyenhavan/Course_Data/main/count.csv")

fig, ax = plt.subplots(figsize=(15, 8))

drought_types = count['Drought types'].unique()
palette = {drought_type: color
           for drought_type, color in zip(drought_types, sns.color_palette('YlOrRd', len(drought_types)))}
all_years = range(count['Year'].min(), count['Year'].max() + 1)
sns.set_style('darkgrid')
for year in all_years:
    year_data = count[count['Year'] == year]
    if len(year_data) > 0:
        # reindex is needed to make sure all drought_types are present
        hue_order = year_data.groupby('Drought types').size().reindex(drought_types).sort_values(ascending=True).index
        sns.countplot(x='Year', order=all_years,
                      hue='Drought types', hue_order=hue_order,
                      data=year_data, palette=palette, ax=ax)

# handles, _ = ax.get_legend_handles_labels()
# handles = handles[:len(drought_types)]
handles = [plt.Rectangle((0, 0), 0, 0, color=palette[drought_type], label=drought_type)
           for drought_type in drought_types]
ax.legend(handles=handles, loc="upper right", frameon=True, bbox_to_anchor=(0.995, 0.99))
plt.show()