如何用两条斜线绘制一条线使用python

问题描述:

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

   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() 

enter image description here

您可能会过度怀疑问题。有在画面两条线段:

  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值的模式。下面是结果:

enter image description here

现在让我们假设你真的想用量化的一些模糊的原因。你会想先计算所有的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() 

enter image description here

+0

@疯狂的物理学家:这是解决问题的数值方法[或多或少像隐式方法],其中第一行的最终值是第二行的初始点。您的代码是数值方法答案。这正是我所期待的。 – HEMS

+0

整洁。如果它有帮助,upvote也会很好:) –

按照你的代码,你应该修改的主要部分是这样的:

x=np.linspace(0,10,1000) 
m = np.empty(x.shape) 
c = np.empty(x.shape) 

m[(x<L)] = 1.0 
c[x<L] = 0 
m[(x>L)] = 0.75 
c[x>L] = L*(1.0 - 0.75) 

y=m*x+c 

plt.plot(x,y) 

注意c需要改变,以及对线是连续的。这是结果:enter image description here

+0

你肯定你的'C'的计算? –

+0

如果您是,请您发布结果图片吗? –

+0

@疯狂的物理学家:对于低于1的任何斜率值,该行必须是连续的。 – HEMS