python - 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
解决方案
如果您不需要有序条,您可以直接绘制数据框并让 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()
推荐阅读
- ruby - 在Ruby中使用方括号调用函数时如何获取args
- html - 如何在没有 iframe 的情况下获得全屏 div?
- laravel - 我在使用“AXIOS PATCH”方法时遇到问题
- django - django) request.POST 方法给了我错误:querydict 对象不可调用
- ios - 将解密的字符串转换为 JSON 对象
- javascript - 网站在启动端口 80 的错误 EADDRINUSE 后一段时间后崩溃
- nestjs - 通过nestjs从url下载图片
- c# - 如何推断源文件中的关系
- python - 气流 - 如何使用来自另一个传感器任务的传感器
- python - 将 pandas 数据框写入 AWS athena 数据库