HEMS - 1 year ago 84

Python Question

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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:

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**