Skip to main content
 首页 » 编程设计

python之你如何使用python绘制一条有两个斜率的线

2024年10月17日8luoye11

我正在使用下面的代码绘制一条具有两个斜率的线,如图所示。斜率应该在一定限制后下降 [limit=5]。我正在使用矢量化方法来设置斜率值。是否有任何其他方法来设置斜率值。有人可以帮助我吗?

                import matplotlib.pyplot as plt 
                import numpy as np 
 
                #Setting the condition 
                L=5 #Limit 
                m=1 #Slope 
                c=0 #Intercept 
 
                x=np.linspace(0,10,1000) 
                #Calculate the y value 
                y=m*x+c 
 
                #plot the line 
                plt.plot(x,y) 
 
                #Set the slope values using vectorisation 
                m[(x<L)] = 1.0 
                m[(x>L)] = 0.75 
 
                # plot the line again 
                plt.plot(x,y) 
 
                #Display with grids 
                plt.grid() 
                plt.show() 

请您参考如下方法:

你可能想多了。图中有两条线段:

  1. 从 (0, 0) 到 (A, A')
  2. 从(A,A')到(B,B')

你知道 A = 5,m = 1,所以 A' = 5。您还知道 B = 10。鉴于 (B' - A')/(B - A) = 0.75,我们有 B' = 8.75。因此,您可以按如下方式制作情节:

from matplotlib import pyplot as plt 
m0 = 1 
m1 = 0.75 
x0 = 0     # Intercept 
x1 = 5     # A 
x2 = 10    # B 
y0 = 0                    # Intercept 
y1 = y0 + m0 * (x1 - x0)  # A' 
y2 = y1 + m1 * (x2 - x1)  # B' 
 
plt.plot([x0, x1, x2], [y0, y1, y2]) 

希望您能看到针对给定一组限制计算 y 值的模式。这是结果:

现在假设您出于某些不明原因确实想要使用矢量化。您可能希望预先计算所有 y 值并绘制一次,否则您会得到奇怪的结果。以下是对原始代码的一些修改:

from matplotlib import pyplot as plt 
import numpy as np 
 
#Setting the condition 
L = 5 #Limit 
x = np.linspace(0, 10, 1000) 
lMask = (x<=L)  # Avoid recomputing this mask 
 
# Compute a vector of slope values for each x 
m = np.zeros_like(x) 
m[lMask] = 1.0 
m[~lMask] = 0.75 
 
# Compute the y-intercept for each segment 
b = np.zeros_like(x) 
#b[lMask] = 0.0   # Already set to zero, so skip this step 
b[~lMask] = L * (m[0] - 0.75) 
 
# Compute the y-vector 
y = m * x + b 
 
# plot the line again 
plt.plot(x, y) 
 
#Display with grids 
plt.grid() 
plt.show()