Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Plotting with Numpy and Pyplot

I am trying to plot a function that is defined conditionally. Specifically: U(x) = (2**delta)/((D-d)**delta)*(D/2 - (x-x0))**delta , for abs(x-x0) less than D/2 and 0 otherwise.

But my problem is that I want to have x, x0 as numpy arrays, because this is how I use them in the rest of my actual code.

I have set-up the following example:

import numpy as np
import matplotlib.pyplot as plt
AD = 0.2
D = 0.4
delta = 8

def Parabolic(x, delta, D, AD):
    x0 = np.round(x)
    tempx = np.abs(x-x0)
    tempD = D/2*np.ones(len(x))
    if tempx<tempD:
        return ((2**delta)/(D-AD)**delta)*(D/2 - (x-x0))**delta
    else:
        return 0

figure = plt.figure(figsize=(10,8), dpi=72)  
xmin = -1.0
xmax = 1.0
X = np.linspace(xmin,xmax,1000)
plt.plot(X, Parabolic(X, delta=8, D=0.4, AD=0.2))

Obviously this example does not work, since the line tempx<tempD raises the error that a Truth-value of a list is ambiguous.

I searched around the documentation of numpy and found the function np.less(tempx, tempD). But if I replace tempx < tempD with np.less(tempx, tempD) it still doesn't work since once again I am asking for a truth value of an entire list. I understand that the problem is not with numpy, but with my inability to understand how to use the logical functions that numpy provides.

I am sorry if this answered some way in another post, I searched in this forum but could not find something else besides the curve() method. However I want to keep my numpy.array format for use in my actual codes. I would bet that the answer must be very simple, I just can't think of it.

like image 847
George Datseris Avatar asked Dec 05 '25 14:12

George Datseris


1 Answers

Try this which uses numpy logical arrays:

import numpy as np
import matplotlib.pyplot as plt
AD = 0.2
D = 0.4
delta = 8

def Parabolic(x, delta, D, AD):
    rtn_arr = np.zeros(len(x))
    x0 = np.round(x)
    tempx = np.abs(x-x0)
    tempD = D/2*np.ones(len(x))
    lgc_arr = tempx<tempD
    x_cut = x[lgc_arr]
    x0_cut = x0[lgc_arr]
    rtn_arr[lgc_arr] = ((2**delta)/(D-AD)**delta)*(D/2 - (x_cut-x0_cut))**delta
    return rtn_arr

figure = plt.figure(figsize=(10,8), dpi=72)
xmin = -1.0
xmax = 1.0
X = np.linspace(xmin,xmax,1000)
plt.plot(X, Parabolic(X, delta=8, D=0.4, AD=0.2))
like image 169
Xirtaminu Avatar answered Dec 08 '25 05:12

Xirtaminu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!