Kai Mason
Kai Mason

Reputation: 41

PYTHON: line of best fit for multiple y values per x value

I am plotting a 1d array (x-axis) against a 2d array (y-axis)in matplotlib so there are multiple y values for each x value. I want to plot a straigt line of best fit (linear regression), not just a line joining the points. How can I do this???

All the otehr examples seem to only have one y value per x value. When I use 'from sklearn.linear_model import LinearRegression' I get as many best fit lines as there are y values per x value.

EDIT: here is the code I have tried:

model = LinearRegression()
x_axis2 = np.arange(0,len(av_rsq3))
x_axis2 = x_axis2.reshape(-1,1)
model.fit(x_axis2, av_rsq3)
pt.figure()
pt.plot(x_axis2,av_rsq3, 'rx')
pt.plot(x_axis2, model.predict(x_axis2))

note: x_axis2 is a 1d array and av_rsq3 is a 2d array.

Upvotes: 4

Views: 6148

Answers (3)

G. Anderson
G. Anderson

Reputation: 5955

If you just want to plot the y values and a line averaging between them, this is possible. Borrowing the dummy data from another answer:

x = [1,2,3,4]

y = [4,6,2,7]
y1 = [2,3,6,8]

plt.scatter(x,y)
plt.scatter(x,y1)
plt.plot(x,[((y[i]+y1[i])/2) for i in range(len(y))])

enter image description here

Upvotes: 0

Namyts
Namyts

Reputation: 405

You just need to add these points with matching x-values as normal points, then you can add a line of best fit as follows:

import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt

x = np.array([1,2,3,4,5,6,6,6,7,7,8])
y = np.array([1,2,4,8,16,32,34,30,61,65,120])

# Fit with polyfit
b, m = polyfit(x, y, 1)

plt.plot(x, y, '.')
plt.plot(x, b + m * x, '-')
plt.show()

which produces graph.
Note, a straight line doesn't fit my example data, but I didn't think about that when writing it :) With polyfit you are also able to change the degree of the fit, as well as obtain error margins in gradients* and offsets.

* (or other polynomial coefficients)

Upvotes: 1

Peter Valtersson
Peter Valtersson

Reputation: 31

What you need to do is provide a one to one mapping. The order the points appear in does not matter. So if you have something like this

X:  [1,2,3,4]
Y1: [4,6,2,7]
Y2: [2,3,6,8]

you would get this

X: [1,2,3,4,1,2,3,4]
Y: [4,6,2,7,2,3,6,8]

Upvotes: 0

Related Questions