如何使用python绘制具有两个坡度的直线

2024-05-14 18:08:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的代码绘制一条带有两个坡度的直线,如图片。那个坡度应在某个极限[极限=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


Tags: the方法代码importplotasnpline
2条回答

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

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

你知道A = 5m = 1,所以A' = 5。你也知道B = 10。鉴于(B' - A') / (B - A) = 0.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值并绘制一次,否则你会得到奇怪的结果。以下是对原始代码的一些修改:

^{pr2}$

enter image description here

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

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

相关问题 更多 >

    热门问题