Skip to content Skip to sidebar Skip to footer

How Do You Plot A Line With Two Slopes Using 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

Solution 1:

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

  1. From (0, 0) to (A, A')
  2. 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:

enter image description here

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

enter image description here

Solution 2:

Following your code, you should modify the main part like this:

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)

Note that c needs to change as well for the line to be continuous. This is the result: enter image description here

Post a Comment for "How Do You Plot A Line With Two Slopes Using Python"