Home > Mobile >  How to plot data like points and draw line of linear fit in python?
How to plot data like points and draw line of linear fit in python?

Time:08-29

I have data where I have 'count_t' in range 1 to 700 and 'Congestion' values in range 0 to 1. I have plotted it as (check plot here)

1

but I wanted to change line joining data only in points at each value and wanted to draw linear fit line through data and How can I maintain aspect ratio of inside grid 1:1?

I will be grateful if you can suggest changes to do the same, Thank you!

CodePudding user response:

You can use inbuilt polyfit function to get linear fit value based on least square method for your data. But I am not aware how to maintain aspect ratio of inside grid 1:1.

# Calculating parameters (Here, intercept-theta1 and slope-theta0)
# of the line using the numpy.polyfit() function
theta = np.polyfit(x, y, 1)
print(f'The parameters of the line: intercept,slope {theta}')

# Now, calculating the y-axis values against x-values according to
# the parameters theta0, theta1 
y_line = theta[1]   theta[0] * x

fig, ax = plt.subplots(figsize=(8,8))
ax.scatter(x,y_con)
ax.plot(x,y_line, 'r')
  • Related