0

I am trying to plot a linear regression line for the following x and y data. It always can show up the scatter plot of (x,y), but it can never draw me the regression line!

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# this part is about the calculation of x and y. It is correct. The problem occurs in the following part to draw the linear regression line!

x = [x_julia, x_mandelbrot]
y = [y_julia, y_mandelbrot]
plot_x_byScales([x_julia, x_mandelbrot], ['julia','mandelbrot'], ylabel="A")
plot_y_byScales([y_julia, y_mandelbrot], ['julia','mandelbrot'], ylabel="B")
plt.plot(y_julia, x_julia, 'o', color='red',label='julia')
plt.plot(y_mandelbrot, x_mandelbrot, 'o', color='blue',label='mandelbrot')
plt.xlabel('B',fontsize=16)
plt.ylabel('A',fontsize=16)
X = x_julia
Y = y_julia
plt.plot(X, Y, 'o')
m, b = np.polyfit(X, Y, 1)
m = slope, b=intercept
plt.plot(X, m*X + b)

please help me to figure out how to plot this regression line!

Daniel L
  • 31
  • 6
  • If that linked question solves your problem please mark it as a duplicate. And I see you have another question exactly like this one from some days ago but with no answers, please delete that one as well so we help curate the site content. – RichieV Sep 05 '20 at 05:53
  • it has been deleted. – Daniel L Sep 07 '20 at 08:27

1 Answers1

1

As explained in the flagged question, you can use np.poly1d to create a line with m and b. This method is a constructor that returns a callable.

p = np.poly1d([m, b])

Then plot with

plt.plot(x, p(x))
RichieV
  • 5,103
  • 2
  • 11
  • 24
  • thanks, RichieV. Because I don't ready know how to insert your two formula to the original code. so, can you show me in detail where I can insert them in my code? Thank you a lot! – Daniel L Sep 05 '20 at 05:44
  • 1
    @DanielL Remove the last two lines in your code and include these two from the answer – RichieV Sep 05 '20 at 05:49
  • Hello, RichieV. I tried many times by using your two-line coding, but the code just never works. It doesn't show me any regression line as the fitting line. Is that possible to ask you to look over my code and see what's wrong? – Daniel L Sep 07 '20 at 08:27