Trend curve through data jumps back and forth when it should be smooth
<p>I want to plot a trend curve of my data points. 
I did that with this code with an exponential model: </p>

<pre><code>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()
</code></pre>

<p>But I obtained this result:</p>

<p><img src="http://i.stack.imgur.com/wktjr.png" alt="enter image description here">]</p>

<p><strong>Question</strong></p>

<p>How can I obtain a smooth trend curve through this data?</p>

<p>One way, you can put <code>x.sort()</code> in before plotting:</p>

<pre><code>x.sort()
ypredict=func(x, *popt)
</code></pre>

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

<pre><code># 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)    
</code></pre>

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

python curve points trend