Adding a trendline over a scatter plot

Multiple plot types can be overlaid on top of each other. For example, we can add a trendline over a scatter plot. The following is an example of adding a trendline to 10 y coordinates with slight deviations from a linear relationship with the x coordinates:

import numpy as np
import matplotlib.pyplot as plt

# Generate th
np.random.seed(100)
x = list(range(10))
y = x+np.random.rand(10)-0.5

# Calculate the slope and y-intercept of the trendline
fit = np.polyfit(x,y,1)

# Add the trendline
yfit = [n*fit[0] for n in x]+fit[1]
plt.scatter(x,y)
plt.plot(yfit,'black')

plt.show()

We can observe from the following plot that the trendline overlays the upward sloping dots:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.37.5