3

How can I make an estimated line like that using matplotlib.

Graph generated using excel

I have several points and I plotted them using matplotlib using the following code:

import matplotlib.pyplot as plt
for smp, lbl in zip(samples, labels):
    plt.scatter(smp[0], smp[1], marker='*', cl = 'b', s=100, label=lbl)

# set limit, xlabel, ylabel, legend ...
# ...

plt.show()

Thanks,

1
  • You should not plot every single point with it's own scatter command. It takes long and if you want to have a legend, you will have an entry for each point. You could use this: x = [value[0] for value in samples] y = [value[1] for value in samples] Commented Jul 25, 2014 at 10:35

1 Answer 1

1

Use polyfit to do linear regression:

import matplotlib.pyplot as plt
from pylab import polyfit, poly1d

x, y = zip(*samples)

fit = polyfit(x, y, 1)
fit_fn = poly1d(fit)
plt.plot(x,y, '*', x, fit_fn(x), 'k')

plt.show()

Example result:

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

I think you just want fit=polyfit(smp[0],smp[1],1) as smp[0] is array like if its the first argument in plt.scatter. or just do x=smp[0]; y=smp[1]
@Gabriel No, according to the OP's for loop, the sample array would be of the format [[x1, y1], [x2, y2], [x3, y3], ..]. So sorting x and y first (one way of another) seems necessary.
right, I see it now. was expecting multiple items in the legend of the OP plot if that was the case, but realize now that the OP code didn't make that image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.