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>From what I can see, the x values on your plots are not sorted in ascending order. The plot does what it should and connects the dots, but they are in such an order that the line jumps "back" and "forward" on the x-axis. Now - you can't see that on the linear plot as everything is on a single line, but starts to become visible on the quadratic. If you sort the points used for the line based on ascending x-value that should do it.</p>

python matplotlib