首页 > 解决方案 > Pandas Seaborn FacetGrid 在每个图上都有相同的 x 标签,但 y 值不同

问题描述

我正在尝试使用条形图显示 FacetGrid,以便它显示黄牌计数 (y) 和球队名称 (x) 的数据,除以不同的足球联赛(其他图应显示其他联赛和其他球队名称)。数据计算正确,但显示仅显示每个地块上的第一个联赛。

这是我用来构建 FacetGrid 的代码片段:

df_alt2_teams = df_alt2.groupby(['league', 'squad'])['cards_yellow', 'cards_red'].sum().reset_index()
df_alt2_teams = df_alt2_teams.sort_values(by=['cards_yellow', 'cards_red'], ascending=True)
g = sns.FacetGrid(df_alt2_teams, col='league', height=8, aspect=4)
g = g.map(sns.barplot, 'squad', 'cards_yellow', palette="flare", data=df_alt2_teams)
g.set(ylim=(0, 50))
g.set_xticklabels(rotation=90)

数据不同,但标签不

数据示例:

index   league          squad       cards_red   cards_yellow
52      Ligue 1         Strasbourg  1.0         2.0
57      Premier League  Brighton    1.0         3.0

标签: pythonpandasseaborn

解决方案


如果您不需要有序条,您可以直接绘制数据框并让 seaborn 进行所有计算:

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

#test data generation 
import numpy as np
n=30
np.random.seed(123)
df_alt2 = pd.DataFrame({"index": np.arange(n), 
                        "league": "Ligue 1", 
                        "squad": np.random.choice(list("ABCDXYZ"), n), 
                        "cards_red": np.random.randint(0, 3, n),
                        "cards_yellow": np.random.randint(0, 5, n)})
df_alt2.loc[:, "league"][df_alt2.squad.isin(list("XYZ"))] = "Premier League"
                 
g = sns.catplot(data=df_alt2, x="squad", y="cards_yellow", col="league", 
                kind="bar", estimator=sum, ci=None, sharex=False)

g.set(ylim=(0, 20))
g.set_xticklabels(rotation=90)
plt.tight_layout()
plt.show()

样本输出: 在此处输入图像描述

我不知道如何说服 seaborn 按价值订购酒吧。因此,在这种情况下,您可能必须恢复到预先计算:

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

#test data generation 
import numpy as np
n=30
np.random.seed(123)
df_alt2 = pd.DataFrame({"index": np.arange(n), 
                        "league": "Ligue 1", 
                        "squad": np.random.choice(list("ABCDXYZ"), n), 
                        "cards_red": np.random.randint(0, 3, n),
                        "cards_yellow": np.random.randint(0, 5, n)})
df_alt2.loc[:, "league"][df_alt2.squad.isin(list("XYZ"))] = "Premier League"
                 

df_alt2_teams = df_alt2.groupby(['league', 'squad'])['cards_yellow', 'cards_red'].sum().reset_index()
df_alt2_teams = df_alt2_teams.sort_values(by=['cards_yellow', 'cards_red'], ascending=True)

g = sns.catplot(data=df_alt2_teams, x="squad", y="cards_yellow", col="league", kind="bar", sharex=False)

g.set(ylim=(0, 20))
g.set_xticklabels(rotation=90)
plt.tight_layout()
plt.show()

输出: 在此处输入图像描述


推荐阅读