How can I plot line segments in python? Here's an example of the lines I want to plot alongside scatterplot data. However, in this example, the line with slope of 1 should run from 0 to 3 only, and the line with slope of -1 should run from 4 to 8 only. I have the slope and intercept of each line, as well as the starting and ending x values.
plt.scatter(x_1, y_1)
plt.axline((0,9), slope = -1, color = 'black')
plt.axline((0,0), slope = 1, color = 'black')
plt.show()
CodePudding user response:
I'm not sure from your output but it looks like you have maybe two different data sets which you want to plot straight lines through. Below I am breaking 3 of your data points into two lists of x, y coordinates, and the other 4 into two lists of x, y coordinates.
Here is the link for the line of best fit one liner
import matplotlib.pyplot as plt
import numpy
# data which you want to fit lines through
x1 = [0, 1, 3]
y1 = [0, 1, 3]
x2 = [4, 5, 6, 8]
y2 = [5, 4, 3, 2]
# plots the two data set points
plt.scatter(x1, y1, color='black')
plt.scatter(x2, y2, color='blue')
# plot will connect a line between the range of the data
plt.plot(x1, y1, color='black')
plt.plot(x2, y2, color='blue')
# line of best fit one liner
plt.plot(np.unique(x1), np.poly1d(np.polyfit(x1, y1, 1))(np.unique(x1)),color='red')
plt.plot(np.unique(x2), np.poly1d(np.polyfit(x2, y2, 1))(np.unique(x2)), color='red')
plt.ylim([-1, 7])
plt.show()
CodePudding user response:
By knowing both the intercept and the slope of your lines, you can essentially use the equation for a straight line to get the corresponding y-values of your endpoints on the x-axis. Then you can plot these points and style the plot to get a black line between the points. This solution looks like the following
import matplotlib.pyplot as plt
import numpy as np
slope1, intercept1 = 1, 0
slope2, intercept2 = -1, 9
l1x = np.array([0,3])
l1y = l1x*slope1 intercept1
l2x = np.array([4,8])
l2y = np.array(l2x*slope2 intercept2)
plt.plot(l1x, l1y, 'k-', l2x, l2y, 'k-')
# The following two lines are to make the plot look like the image in the question
plt.xlim([0,8])
plt.ylim([0,9])
plt.show()
CodePudding user response:
The line can be defined either by two points xy1 and xy2, or by one point xy1 and a slope.
plt.scatter(x_1, y_1)
plt.axline((4,4), (8,0), color = 'blue')
plt.axline((0,0), (3,3), color = 'black')
plt.show()