python画抛物线,如何使用python绘制具有两个斜率的线

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

m[(x>L)] = 0.75

# plot the line again

plt.plot(x,y)

#Display with grids

plt.grid()

plt.show()

3dtgA.png

解决方案

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

From (0, 0) to (A, A')

From (A, A') to (B, B')

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

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

o1iIM.png

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

1afa7.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值