python – Numpy和Pyplot的条件绘图

我试图绘制一个有条件定义的函数.特别:

U(x)=(2 ** delta)/((Dd)** delta)*(D / 2 – (x-x0))** delta,abs(x-x0)小于D / 2和0除此以外.

但我的问题是我希望将x,x0作为numpy数组,因为这是我在其余实际代码中使用它们的方式.

我已经设置了以下示例:

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

显然,这个例子不起作用,因为行tempx< tempD引起了列表的真值 – 值不明确的错误. 我搜索了numpy的文档并找到了函数np.less(tempx,tempD).但如果我取代tempx

最佳答案 试试这个使用numpy逻辑数组:

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))
点赞