英文:
Line plot not appearing
问题
I am trying to plot a chart with multiple plots like line, scatter etc., The line plot I'm 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()
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 Evolution\nFrom 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")
Here is the plot:
What is the mistake I'm doing?
英文:
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()
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 Evolution\nFrom 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")
What is the mistake I'm doing?
答案1
得分: 2
以下是翻译好的部分:
问题出现在散点图的代码中...如果您看第一个图的 x 轴,您会发现它们都是数字。如果您打印 df['PR'].rolling(30).mean()
,它将是一个数字列表。另一方面,散点图都是针对日期绘制的。将线图更改为 plt.plot(df['Date'], df['PR'].rolling(30).mean(), label='30-d moving avg of pr')
(基本上添加 df.Date 作为 x 轴应该可以工作。我使用一些虚拟数据进行了测试,似乎可以正常工作。完整的代码和图如下...
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 Evolution\nFrom 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') #未显示出来的部分
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")
希望这能帮助您解决问题。如果您需要进一步的帮助,请告诉我。
<details>
<summary>英文:</summary>
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 Evolution\nFrom 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][1]][1]
[1]: https://i.stack.imgur.com/DE3wj.png
</details>
# 答案2
**得分**: 0
你想绘制一条水平线吗?
请尝试 `pyplot.axhline(y=somevalue)`
而在你的情况下,使用
ax.axhline(y=df['PR'].rolling(30).mean(),label='30-d moving avg of pr',color='r', linestyle='--')
<details>
<summary>英文:</summary>
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='--')
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论