【问题标题】:How do you plot a line with two slopes using python你如何使用python绘制一条有两个斜率的线
【发布时间】:2016-08-03 02:46:29
【问题描述】:

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

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    你可能想多了这个问题。图中有两条线段:

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

    你知道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 值的模式。结果如下:

    现在假设您确实出于某种模糊的原因想要使用矢量化。您可能希望预先计算所有 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()
    

    【讨论】:

    • @疯狂物理学家:这是解决问题的数值方法[或多或少类似于隐式方法],其中第一行的最终值是第二行的初始点。您的代码是数值方法答案。这正是我想要的。
    【解决方案2】:

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

    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 也需要更改以使行连续。结果如下:

    【讨论】:

    • 你确定你对c的计算吗?
    • 如果是,能否请您发布结果图片?
    • @疯狂物理学家:对于任何低于 1 的斜率值,这条线都必须是连续的。
    • 我的错误,我没有计算出正确的截距公式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2019-04-09
    • 1970-01-01
    相关资源
    最近更新 更多