如何在 python 中繪制線段?這是我想在散點圖資料旁邊繪制的線條示例。但是,在此示例中,斜率為 1 的線應僅從 0 延伸到 3,而斜率為 -1 的線應僅從 4 延伸到 8。我有每條線的斜率和截距,以及開始和結束的 x 值。
plt.scatter(x_1, y_1)
plt.axline((0,9), slope = -1, color = 'black')
plt.axline((0,0), slope = 1, color = 'black')
plt.show()

uj5u.com熱心網友回復:
我不確定您的輸出,但看起來您可能有兩個不同的資料集,您想通過這些資料集繪制直線。下面我將您的 3 個資料點分成兩個 x、y 坐標串列,將另外 4 個資料點分成兩個 x、y 坐標串列。
這是最適合的一條線的鏈接
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()
uj5u.com熱心網友回復:
通過知道直線的截距和斜率,您基本上可以使用直線方程來獲得 x 軸上端點的相應 y 值。然后,您可以繪制這些點并設定繪圖樣式以在點之間獲得一條黑線。此解決方案如下所示
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()
uj5u.com熱心網友回復:
這條線可以由兩個點 xy1 和 xy2 定義,也可以由一個點 xy1 和一個斜率定義。
plt.scatter(x_1, y_1)
plt.axline((4,4), (8,0), color = 'blue')
plt.axline((0,0), (3,3), color = 'black')
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433236.html
標籤:Python matplotlib
