【问题标题】:Line plot doesn't show when used with a datetime variable on the x-axis与 x 轴上的日期时间变量一起使用时,线图不显示
【发布时间】:2021-09-18 09:36:25
【问题描述】:

我正在尝试绘制一个带有两个折线图的条形图。条形图显示正常,但我似乎无法在条形图上方绘制线条。代码如下:

fig, ax = plt.subplots(figsize=(18,9))
sns.set_style("darkgrid")
g=sns.barplot(date_new, df["Net xG (xG - Opponent's xG)"].astype("float"), palette="coolwarm_r", hue=df["Net xG (xG - Opponent's xG)"].replace({"-":0}).astype("float"), dodge=False, data=df)
plt.plot(date_new, -df["Opponent's xG"].astype("float"), color="gold", marker="o")
plt.plot(date_new, df["xG (Expected goals)"].astype("float"), color="indianred", marker="o")
g.set_xticklabels(stuff[::-1], rotation=90)
g.get_legend().remove()
g.set(xlim=([-0.8, 46]))
plt.show()

date_new 用于 x 轴的变量采用 datetime64[ns] 格式。我注意到的一件奇怪的事情是,如果我将date_new 重新格式化为date_new.astype("str") 之类的字符串,则会显示线图,但顺序会颠倒。

我试图通过将 x 轴变量更改为 date_new[::-1] 来“重新反转”日期排序的顺序,但这似乎并没有改变线图的顺序。

这是 x(日期)和 y(xG)轴变量在数据框上的显示截图:

【问题讨论】:

  • 刻度标签是化妆品。更改标签不会重新排序绘图。 str 排序和日期时间排序会有所不同。一些用于重现情节的样本数据以及一些预期的输出将使回答这个问题更容易。
  • 您的 x 轴在日期中很明显不是。我不知道 seaborn 是如何工作的,但我希望设置 data=df 会导致 x 轴是分类的,类别是您沿 xaxis 看到的字符串。
  • @HenryEcker 我无法共享数据,因为它可能会导致一些版权问题,但是如果我要描述轴变量:-y: 我正在尝试绘制整个赛季每场比赛的预期进球数 (xG) 变化。红线应该代表所提到的俱乐部在特定比赛中产生的 xG,而黄色则代表在该比赛中反对该俱乐部产生的 xG。 xG 和 xG against 是 0-5 之间的浮点数。 -x: 我正在尝试根据日期时间变量按时间顺序绘制 xGs 的变化。
  • @JodyKlymak 我使用的数据是足球俱乐部每场比赛产生的目标期望值。我在 x 轴上使用日期时间数据,我用字符串替换了轴标签,这些字符串是我正在分析的俱乐部在这些日期与之交手的足球俱乐部的名称。我的目标是切换两个线图的起点和终点。
  • @HenryEcker 我添加了我正在使用的列的屏幕截图。问题是两个折线图上的第一个点对应于图表上的最后一个条形。所以线图是倒置的。标签和条是正确的。除非我将日期时间列更改为字符串,否则线图根本不会显示。

标签: python pandas matplotlib seaborn visualization


【解决方案1】:

您正在尝试将条形图与两个折线图结合起来。您似乎在匹配 x 轴变量时遇到问题。正如@Henry Ecker 上面所说,条形图上的 x 轴标签是装饰性的,并不代表实际的日期时间轴。因此,条形图的 x 轴值只是数字 0 到 46。

要解决您的问题,只需将线图 x 值设为 0 到 46 的列表。

我模拟了您的数据并在下面的示例中演示了解决方案。

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

# create data 
# there are 46 rows each representing a game against some other club
# colums include: date of game, opposing club, club goals, opposing club goals
# goal range is 0-5

df = pd.DataFrame({
    'date':pd.date_range(start='1/2021', end='7/1/2021', periods=46),
    'club':['Team: ' + str(n) for n in range(1,47)],
    'goals': np.random.randint(0, 5, 46),
    'opposing_goals':np.random.randint(0, 5, 46)
})

df['net_goals'] = df.goals - df.opposing_goals

fig, ax = plt.subplots(figsize=(18,9)) 
sns.set_style("darkgrid")              

g=sns.barplot(
    x=df.date, y=df.net_goals, 
    palette="coolwarm_r", hue=df.net_goals, dodge=False, data=df
    )

plt.plot(np.arange(0,46), -df.opposing_goals, color="gold", marker="o") 
plt.plot(np.arange(0,46), df.goals, color="indianred", marker="o")

g.set_xticklabels(df.club, rotation=45)
g.get_legend().remove()
g.set(xlim=([-0.8, 46]))

【讨论】:

  • 首先,对于我在最初的问题中所能提供的信息量有限,我们深表歉意。我对 Stack Overflow 和 Python 还有些陌生。使用np.arange() 确实解决了我的问题。我很感激,感谢你经历了所有的麻烦来帮助一个陌生人。非常感谢它。
猜你喜欢
  • 1970-01-01
  • 2021-06-24
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
相关资源
最近更新 更多