Skip to content
Advertisement

Pyplot start x axis at negative values

I am trying to plot a piecewise function, but at the moment I am getting an error message when I try to start my x values at a negative. The code works fine if I run the following (albeit with only one part of the function):

x = np.linspace(0, 100, 100)
y = np.piecewise(x, [x < 0, x >= 0], [0, (1/100)*x*np.exp(-x/10)])
z = -np.exp(-x/10)*((x/10)+1)+1
plt.plot(x, y, 'r', label='test')
plt.legend(loc='right')
plt.show()

But when I change the first line to

x = np.linspace(-100, 100, 100)

I get thrown the error message: “NumPy boolean array indexing assignment cannot assign 100 input values to the 50 output values where the mask is true”

Any help would be greatly appreciated.

Advertisement

Answer

Based on the examples provided in the docs:

y = np.piecewise(x, [x < 0, x >= 0], [0, lambda x: (1/100)*x*np.exp(-x/10)])

Output:

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement