折线图未显示

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

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=&#39;red&#39;)
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(&quot;Performance Ratio Evolution\nFrom 2019-07-01 to 2022-03-24&quot;, fontsize=20)
plt.scatter(&#39;Date&#39;, &#39;PR&#39;, data=l2, label=&quot;&lt;2&quot;, marker=&#39;D&#39;, color=&#39;#000080&#39;)
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;)
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;)
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;)
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
plt.legend([&quot;&lt;2&quot;, &quot;2~4&quot;, &quot;4~6&quot;, &quot;&gt;6&quot;])
y = [73.9 * (1 - 0.008) ** i for i in range(4)]
start_date = datetime.strptime(&quot;2019-07-01&quot;, &quot;%Y-%m-%d&quot;)
end_date = datetime.strptime(&quot;2023-03-24&quot;, &quot;%Y-%m-%d&quot;)
dates = []
while start_date &lt;= end_date:
    dates.append(start_date)
    start_date += timedelta(days=365)
plt.step(dates, y, label=&quot;Performance Ratio&quot;, color=&quot;green&quot;)
plt.ylim(0, 100)
date_fmt = mdates.DateFormatter(&#39;%b/%y&#39;)
ax.xaxis.set_major_formatter(date_fmt)
ax.set_xlim([date(2019, 7, 1), date(2022, 3, 24)])
plt.ylabel(&quot;Performance Ratio (%)&quot;)
plt.legend(loc=&quot;center&quot;)
# 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 轴应该可以工作。我使用一些虚拟数据进行了测试,似乎可以正常工作。完整的代码和图如下...

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[&#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")


[![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>

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:

确定