如何在python中创建逐年绘图

问题描述

我有以下df

player  season pts
  A      2017   6
  A      2018   5
  A      2019   9
  B      2017   2
  B      2018   1
  B      2019   3
  C      2017   10
  C      2018   8
  C      2019   7

我想作一个图来考察pts的同比稳定性。也就是说,我想看看pts在逐年的基础上有多相关。我尝试了各种方法来绘制此图,但似乎无法完全正确。这是我最初尝试的方法

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

for i in df.season:
  sns.scatterplot(df.pts.iloc[i],df.pts.iloc[i]+1)

plt.xlabel('WOPR Year n')

plt.ylabel('WOPR Year n+1')

IndexError: single positional indexer is out-of-bounds

我考虑了一下,并认为类似的方法可能有用:

fig,10))

seasons = [2017,2018,2019]

for i in seasons:
  sns.scatterplot(df.pts.loc[df.season==i],df.pts.loc[df.season==i+1])

plt.xlabel('WOPR Year n')

plt.ylabel('WOPR Year n+1')

这没有返回错误,只是给了我一个空白情节。我想我在附近。任何帮助表示赞赏。谢谢!为了澄清起见,我希望每个玩家都被绘制两次。对于x = 2017和y = 2018,一次,对于x = 2018和y = 2019,另一年(因此为n + 1)。编辑:在这里sns.regplot()可能比sns.scatterplot更好,因为我可以根据自己的喜好使用趋势线。下图捕获了每年所需指标的稳定性。

enter image description here

解决方法

我认为您可以做一个自我合并:

sns.lineplot(data=df.merge(df.assign(season=df.season+1),on=['player','season'],suffixes=['_last','_current']),x='pts_last',y='pts_current',hue='player')

输出:

enter image description here

注意:如果您不关心玩家,则可以放弃hue。另外,如果更适合您,请使用scatterplot代替lineplot

,

根据您的第二个想法:

for i in seasons[:-1]:
  sns.scatterplot(df.pts.loc[df.season==i].tolist(),df.pts.loc[df.season==(i+1)].tolist())

似乎有两个问题:一个是Seaborn方法期望数值数据;另一个是将系列转换为列表将摆脱索引,以便Seaborn能够正确处理它。另一个是您需要排除季节的最后一个元素,因为您要针对n绘制n+1