Plot quadratic function / model with matplotlib
<p>I'm playing around with python and want to plot a quadratic linear regression with matplotlib. The problem is, that my plot ends up being a lot of connected lines/dots instead of just the one function:</p>

<p><a href="http://i.stack.imgur.com/EljBs.png" rel="nofollow">Plot</a></p>

<p><a href="http://i.stack.imgur.com/wQxfD.png" rel="nofollow">Zoomed plot</a></p>

<p>Normally I would think of this being a problem with row vs. column vectors. But nothing seems to change when I transpose. </p>

<p>Here's my code:</p>

<pre><code>from sklearn import datasets, linear_model
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Load diabetes dataset JSON
dsDiabetes = datasets.load_diabetes()

# Create feature- and outcome vectors
lin_train  = np.array(dsDiabetes.data[:, np.newaxis, 2])
quad_train = np.concatenate((lin_train, lin_train**2), axis=1)
outcome    = np.array(dsDiabetes.target)

# Create regression objects
lin_model = linear_model.LinearRegression()
quad_model = linear_model.LinearRegression()

# lin_train model
lin_model.fit(lin_train, outcome)
quad_model.fit(quad_train, outcome)

# Plot
plt.style.use('fivethirtyeight')
plt.scatter(lin_train, outcome, color='black')
# plt.plot(lin_train, quad_model.predict(quad_train))
# plt.plot(lin_train, lin_model.predict(lin_train), color='blue', linewidth=1)
plt.plot(lin_train, quad_model.predict(quad_train), color='red', linewidth=1)
plt.show()
</code></pre>

<p>What am I missing?</p>

<p>You need to sort your values. You can take any approach. Personally, I would just use <code>pandas</code> but there are more lightweight solutions for sure.</p>

<pre><code>&gt;&gt;&gt; df = pd.DataFrame({'x':lin_train.reshape((lin_train.shape[0],)), 'y':quad_model.predict(quad_train)})
&gt;&gt;&gt; df.sort_values(by='x', inplace=True)
&gt;&gt;&gt; plt.style.use('fivethirtyeight')
&gt;&gt;&gt; plt.scatter(lin_train, outcome, color='black')
&lt;matplotlib.collections.PathCollection object at 0x7f6bf2906590&gt;
&gt;&gt;&gt; # plt.plot(lin_train, quad_model.predict(quad_train))
... # plt.plot(lin_train, lin_model.predict(lin_train), color='blue', linewidth=1)
... plt.plot(df.x, df.y, color='red', linewidth=1)
[&lt;matplotlib.lines.Line2D object at 0x7f6bf29069d0&gt;]
</code></pre>

<p><a href="http://i.stack.imgur.com/guMDo.png" rel="nofollow"><img src="http://i.stack.imgur.com/guMDo.png" alt="enter image description here"></a></p>

python matplotlib