Matplotlib – Line plot not appearing

Question:

I am trying to plot a chart with multiple plots like line, scatter etc., The line plot Im trying to plot is not showing up on the chart.
I want a line plot like this:

fig, ax = plt.subplots(figsize=(20, 6))
plt.plot(result, color='red')
plt.show()

enter image description here
I want this to show up in my plot shown below.

Here is my code:

fig, ax = plt.subplots(figsize=(20, 10))
fig.suptitle("Performance Ratio EvolutionnFrom 2019-07-01 to 2022-03-24", fontsize=20)
plt.scatter('Date', 'PR', data=l2, label="<2", marker='D', color='#000080')
plt.scatter('Date', 'PR', data=g2l4, label="2~4", marker='D', s=15, color="#ADD8E6")
plt.scatter('Date', 'PR', data=g4l6, label="4~6", marker='D', s=15, color="#FFA500")
plt.scatter('Date', 'PR', data=g6, label=">6", marker='D', s=15, color="#964B00")
plt.plot(df['PR'].rolling(30).mean(),label='30-d moving avg of pr') #The one which is not showing up
plt.legend(["<2", "2~4", "4~6", ">6"])
y = [73.9 * (1 - 0.008) ** i for i in range(4)]
start_date = datetime.strptime("2019-07-01", "%Y-%m-%d")
end_date = datetime.strptime("2023-03-24", "%Y-%m-%d")
dates = []
while start_date <= end_date:
    dates.append(start_date)
    start_date += timedelta(days=365)
plt.step(dates, y, label="Performance Ratio", color="green")
plt.ylim(0, 100)
date_fmt = mdates.DateFormatter('%b/%y')
ax.xaxis.set_major_formatter(date_fmt)
ax.set_xlim([date(2019, 7, 1), date(2022, 3, 24)])
plt.ylabel("Performance Ratio (%)")
plt.legend(loc="center")
# plt.savefig("performance_ratio_evolution.png")

Here is the plot:
enter image description here

What is the mistake I’m doing?

Asked By: Karthik Bhandary

||

Answers:

do you want to plot a horizontal line?
please try pyplot.axhline(y=somevalue)
and in your case, use the

ax.axhline(y=df['PR'].rolling(30).mean(),label='30-d moving avg of pr',color='r', linestyle='--')
Answered By: Zalrahda

The problem is in the scatter plot code… if you look at the first plot x-axis, you will see that they are all numbers. If you print df['PR'].rolling(30).mean(), it will be a list of numbers. On the other hand, the scatter plots are all plotted against dates. Changing the line plot to plt.plot(df['Date'], df['PR'].rolling(30).mean(),label='30-d moving avg of pr') (basically adding df.Date as the x-axis should work. I did this with some dummy data and it appears to work. Full code and plot below…

df=pd.DataFrame({'PR':np.random.uniform(low=60, high=90, size=(100,)),
                'Date':pd.date_range('2019/07/01', periods=100, freq='SM')})
fig, ax = plt.subplots(figsize=(20, 6))
fig.suptitle("Performance Ratio EvolutionnFrom 2019-07-01 to 2022-03-24", fontsize=20)
plt.scatter('Date', 'PR', data=df[0:24], label="<2", marker='D', color='#000080')
plt.scatter('Date', 'PR', data=df[25:49], label="2~4", marker='D', s=15, color="#ADD8E6")
plt.scatter('Date', 'PR', data=df[50:74], label="4~6", marker='D', s=15, color="#FFA500")
plt.scatter('Date', 'PR', data=df[75:99], label=">6", marker='D', s=15, color="#964B00")
plt.plot(df['Date'], df['PR'].rolling(30).mean(),label='30-d moving avg of pr') #The one which is not showing up
plt.legend(["<2", "2~4", "4~6", ">6"])
y = [73.9 * (1 - 0.008) ** i for i in range(4)]
start_date = datetime.datetime.strptime("2019-07-01", "%Y-%m-%d")
end_date = datetime.datetime.strptime("2023-03-24", "%Y-%m-%d")
dates = []
while start_date <= end_date:
    dates.append(start_date)
    start_date += datetime.timedelta(days=365)
plt.step(dates, y, label="Performance Ratio", color="green")
plt.ylim(0, 100)
import matplotlib.dates as mdates
date_fmt = mdates.DateFormatter('%b/%y')
ax.xaxis.set_major_formatter(date_fmt)
ax.set_xlim([datetime.date(2019, 7, 1), datetime.date(2022, 3, 24)])
plt.ylabel("Performance Ratio (%)")
plt.legend(loc="center")

enter image description here

Answered By: Redox
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.