简体   繁体   中英

Trend curve through data jumps back and forth when it should be smooth

I want to plot a trend curve of my data points. I did that with this code with an exponential model:

with open(file,'r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
next(plots)
x=[]
y=[]
for row in plots:
    x.append(float(row[1]))
    y.append(float(row[3]))
plt.plot(x, y, 'ro',label="Original Data")
x = np.array(x, dtype=float) #transform your data in a numpy array of floats 
y = np.array(y, dtype=float) #so the curve_fit can work



def func(x, a, b, c):
    return (a*np.exp(-b*x)+c)

popt, pcov = curve_fit(func, x, y)
ypredict=func(x, *popt)

plt.plot(x, ypredict, '--', label="Fitted Curve")  
plt.legend(loc='upper left')
plt.show()

But I obtained this result:

在此输入图像描述 ]

Question

How can I obtain a smooth trend curve through this data?

One way, you can put x.sort() in before plotting:

x.sort()
ypredict=func(x, *popt)

Another way would be to use something like this (better for a plot in my opinion),

# 1000 evenly spaced points over the range of x values
x_plot = np.linspace(x.min(), x.max(), 1000)
y_plot=func(x_plot, *popt)    

Then use x_plot and y_plot for your trend line and it should look fine. The problem is very-likely that your x values are not monotone and so your line plot is connecting points in the order they appear in x .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM