Python散点图和matplotlib

roejwanj  于 2022-11-15  发布在  Python
关注(0)|答案(3)|浏览(190)

我有一个散点图在python上,我想画一条趋势线。从各种例子,我已经找到周围的互联网上学习如何画趋势线我的代码如下:

import matplotlib.pyplot as plt
import numpy as np

x=np.array([9.80,13.20,13.46,14.09,13.96,10.77,8.79,8.61,8.83,11.08,10.13,12.40,9.90,10.96,12.75,11.79,11.79,12.38,12.78,13.08,12.83,12.57,12.96,12.90,12.91,13.67,12.83,12.50,12.42,12.83,12.82,12.70,12.60,12.90,13.20])
y=np.array([0.0706,0.0969,0.0997,0.1031,0.0848,0.1044,0.0815,0.1030,0.0783,0.0970,0.1193,0.0796,0.0697,0.0738,0.0895,0.0912,0.0887,0.0973,0.0942,0.1052,0.0984,0.0965,0.0903,0.0876,0.1071,0.0872,0.0857,0.0967,0.0926,0.0837,0.0967,0.0935,0.0946,0.0930,0.0758
])

plt.scatter(x, y)
fit = np.polyfit(x, y, deg=4)
p = np.poly1d(fit)
plt.plot(x,p(x),"r--")
plt.show()

但是结果线而不是曲线只是线的混合。有人能解释一下我的错误吗?

2cmtqfgy

2cmtqfgy1#

我认为这是因为x值没有排序。

import matplotlib.pyplot as plt 
import numpy as np

x=np.array([9.80,13.20,13.46,14.09,13.96,10.77,8.79,8.61,8.83,11.08,10.13,12.40,9.90,10.96,12.75,11.79,11.79,12.38,12.78,
            13.08,12.83,12.57,12.96,12.90,12.91,13.67,12.83,12.50,12.42,12.83,12.82,12.70,12.60,12.90,13.20]) 

y=np.array([0.0706,0.0969,0.0997,0.1031,0.0848,0.1044,0.0815,0.1030,0.0783,0.0970,0.1193,0.0796,0.0697,0.0738,
            0.0895,0.0912,0.0887,0.0973,0.0942,0.1052,0.0984,0.0965,0.0903,0.0876,0.1071,0.0872,0.0857,0.0967,0.0926,0.0837,0.0967,0.0935,0.0946,0.0930,0.0758 ])

# Here I sort x values and their corresponding y values
args = np.argsort(x)
x = x[args]
y = y[args]

plt.scatter(x, y) 
fit = np.polyfit(x, y, deg=4) 
p = np.poly1d(fit) 
plt.plot(x,p(x),"r--") 
plt.show()

结果:

nnt7mjpx

nnt7mjpx2#

这将:

plt.scatter(x,y)
x = sorted(x) 
plt.plot(x,p(x),"r--")

诀窍是在x值上绘制线之前对它们进行排序。

e0bqpujr

e0bqpujr3#

[“金牌”、“银”、“铜牌”、“无”],[1,2,3,4],inplace =True)df_medals = df.groupby([“年份”、“奖牌”]).count().reset_index()
移动平均值= df_entries.rolling(窗口=5).mean()
累计总和[:5]
散点图(x=“年份”,y=“ID”,大小=“奖牌”,色调=“奖牌”,数据=df_奖牌[df_奖牌[“奖牌”]!=“无”])散点线图(x=“年份”,y=“ID”,数据=累计总和)

相关问题