0

Since pylab is discouraged, I intend to use matplotlib from this example in https://www.wired.com/2011/01/linear-regression-with-pylab/

from pylab import *

x = [0.2, 1.3, 2.1, 2.9, 3.3]
y = [3.3, 3.9, 4.8, 5.5, 6.9]

(m, b) = polyfit(x, y, 1)
print(m, b)

yp = polyval([m, b], x)
plt.plot(x, yp)
plt.grid(True)
plt.scatter(x,y)
xlabel('x')
ylabel('y')
show()

If I start this one with

import matplotlib.pyplot as plt

I don't know how to replace polyfit and polyval functions in matplotlib. In line 4 and 7, these call the polyfit and polyval function (those are in the pylab module). What functions should I use instead for using matplotlib?

I want to use this example but using matplotlib.

6
  • 3
    Please don’t paste images of your code. Include the actual code so people trying to help you don’t have to transcribe your image. Commented Sep 7, 2018 at 18:12
  • 1
    You are right. The site actually has the image, I'll try typing the code next time. Commented Sep 7, 2018 at 18:17
  • 2
    FYI, you can edit questions and type the code yourself. @MarkMeyer was nice enough to use his own time to do it this time. Commented Sep 7, 2018 at 18:26
  • 2
    As requested, it is done. Thank you. @mark-meyer Commented Sep 7, 2018 at 19:07
  • 2
    It looks good @RakibulHassan -- I didn't downvote this, but if I had I would undo it. Commented Sep 7, 2018 at 19:08

2 Answers 2

3

polyfit and polyval are both available in numpy. So you can simple use:

import numpy as np
import matplotlib.pyplot as plt

x = [0.2, 1.3, 2.1, 2.9, 3.3]
y = [3.3, 3.9, 4.8, 5.5, 6.9]

(m, b) = np.polyfit(x, y, 1)
print(m, b)

yp = np.polyval([m, b], x)
plt.plot(x, yp)
plt.grid(True)
plt.scatter(x,y)

enter image description here

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

3 Comments

Outstanding! As you said, polyfit and polyval are both available in numpy, we could go ahead and use it. Meanwhile, I was planning to use import numpy as np import matplotlib.pyplot as plt x = [0.2, 1.3, 2.1, 2.9, 3.3] y = [3.3, 3.9, 4.8, 5.5, 6.9] to plot and add the best fit line. What could be the best way to plot both with less code? Thank you once again @mark-meyer
Can this be done with Seaborn's regplot or lmplot as shown in stackoverflow.com/a/40478505 ?
I'm sorry for the delay. I thought I accepted both the answers. It seems that, you can only accept one. I didn't want to hurt anyone.
2

The plotting functions are in matplotlib.pyplot but PyLab also includes numerical functions from NumPy which you can with

import numpy as np

np.polyfit(...)  # etc.

(See also the first answer here.)

Comments

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.