折线图未显示

huangapple go评论144阅读模式
英文:

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:

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

I want this to show up in my plot shown below.

Here is my code:

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

  1. fig, ax = plt.subplots(figsize=(20, 6))
  2. plt.plot(result, color=&#39;red&#39;)
  3. plt.show()

折线图未显示
I want this to show up in my plot shown below.

Here is my code:

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

Here is the plot:
折线图未显示

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 轴应该可以工作。我使用一些虚拟数据进行了测试,似乎可以正常工作。完整的代码和图如下...

  1. df = pd.DataFrame({'PR': np.random.uniform(low=60, high=90, size=(100,)),
  2. 'Date': pd.date_range('2019/07/01', periods=100, freq='SM')})
  3. fig, ax = plt.subplots(figsize=(20, 6))
  4. fig.suptitle("Performance Ratio Evolution\nFrom 2019-07-01 to 2022-03-24", fontsize=20)
  5. plt.scatter('Date', 'PR', data=df[0:24], label="<2", marker='D', color='#000080')
  6. plt.scatter('Date', 'PR', data=df[25:49], label="2~4", marker='D', s=15, color="#ADD8E6")
  7. plt.scatter('Date', 'PR', data=df[50:74], label="4~6", marker='D', s=15, color="#FFA500")
  8. plt.scatter('Date', 'PR', data=df[75:99], label=">6", marker='D', s=15, color="#964B00")
  9. plt.plot(df['Date'], df['PR'].rolling(30).mean(), label='30-d moving avg of pr') #未显示出来的部分
  10. plt.legend(["<2", "2~4", "4~6", ">6"])
  11. y = [73.9 * (1 - 0.008) ** i for i in range(4)]
  12. start_date = datetime.datetime.strptime("2019-07-01", "%Y-%m-%d")
  13. end_date = datetime.datetime.strptime("2023-03-24", "%Y-%m-%d")
  14. dates = []
  15. while start_date <= end_date:
  16. dates.append(start_date)
  17. start_date += datetime.timedelta(days=365)
  18. plt.step(dates, y, label="Performance Ratio", color="green")
  19. plt.ylim(0, 100)
  20. import matplotlib.dates as mdates
  21. date_fmt = mdates.DateFormatter('%b/%y')
  22. ax.xaxis.set_major_formatter(date_fmt)
  23. ax.set_xlim([datetime.date(2019, 7, 1), datetime.date(2022, 3, 24)])
  24. plt.ylabel("Performance Ratio (%)")
  25. plt.legend(loc="center")

折线图未显示

  1. 希望这能帮助您解决问题。如果您需要进一步的帮助,请告诉我。
  2. <details>
  3. <summary>英文:</summary>
  4. 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[&#39;PR&#39;].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[&#39;Date&#39;], df[&#39;PR&#39;].rolling(30).mean(),label=&#39;30-d moving avg of pr&#39;)` (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")

  1. [![enter image description here][1]][1]
  2. [1]: https://i.stack.imgur.com/DE3wj.png
  3. </details>
  4. # 答案2
  5. **得分**: 0
  6. 你想绘制一条水平线吗?
  7. 请尝试 `pyplot.axhline(y=somevalue)`
  8. 而在你的情况下,使用

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

  1. <details>
  2. <summary>英文:</summary>
  3. do you want to plot a horizontal line?
  4. please try `pyplot.axhline(y=somevalue)`
  5. and in your case, use the

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

  1. </details>

huangapple
  • 本文由 发表于 2023年6月15日 15:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定