onatto
onatto

Reputation: 15

Line plot doesn't show when used with a datetime variable on the x-axis

I'm trying to plot a bar graph that is accompanied by two line graphs. The barplot shows fine but I can't seem to get the lines plotted above the barplot. Here's the code:

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()

Output of the above code, no line plots

date_new variable used for the x-axis is in datetime64[ns] format. A weird thing I noticed is that if I reformat date_new as a string like date_new.astype("str"), the line plots show but the order is reversed.

I tried to "re-reverse" the order of which dates are sorted by by changing the x-axis variable to date_new[::-1], but that doesn't seem to change the line plots' order. By changing date_new to a string format the line plots get visible, however this time I can't reverse the order of x values which are reversed.

Here's a screenshot of how the x (Date) and y (xG) axis variables look on the dataframe:

Dataframe

Upvotes: 0

Views: 558

Answers (1)

Coup
Coup

Reputation: 740

You are trying to combine a bar graph with two line plots. It seems you are having issues matching your x-axis variables. As @Henry Ecker said above, the x axis labels on a bar plot are cosmetic and do not represent an actual date time axis. Consequently, the x-axis values for your bar plot are simply the numbers 0 to 46.

To fix your problem, simply make the line plot x values a list from 0 to 46.

I simulated your data and demonstrate the solution in the example below.

enter image description here

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]))

Upvotes: 2

Related Questions