如何使用python绘制具有两个斜率的线 [英] How do you plot a line with two slopes using python

查看:541
本文介绍了如何使用python绘制具有两个斜率的线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the below codes to plot a line with two slopes as shown in the picture.The slope should should decline after certain limit [limit=5]. I am using vectorisation method to set the slope values.Is there any other method to set the slope values.Could anyone help me in this?

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

推荐答案

您可能在想这个问题.图片中有两个线段:

You may be overthinking the problem. There are two line segments in the picture:

  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.因此,您可以按以下方式绘制图:

You know that A = 5, m = 1, so A' = 5. You also know that B = 10. Given that (B' - A') / (B - A) = 0.75, we have B' = 8.75. You can therefore make the plot as follows:

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值的计算模式.结果如下:

Hopefully you see the pattern for computing y values for a given set of limits. Here is the result:

现在让我们说您确实出于某些晦涩的原因想要使用向量化.您可能需要先计算所有y值并绘制一次,否则将得到怪异的结果.这是对原始代码的一些修改:

Now let's say you really did want to use vectorization for some obscure reason. You would want to compute all the y values up front and plot once, otherwise you will get weird results. Here are some modifications to your original code:

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

这篇关于如何使用python绘制具有两个斜率的线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆