如何使用python绘制具有两个斜率的线

时间:2016-08-02 18:15:45

标签: python numpy matplotlib

我使用下面的代码绘制一条有两个斜率的线,如图所示。斜率应该在一定限度[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()

enter image description here

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

你可能正在过度思考这个问题。图中有两个线段:

  1. 从(0,0)到(A,A&#39;)
  2. 从(A,A&#39;)到(B,B&#39;)
  3. 您知道A = 5m = 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