此代码绘制正态分布曲线:
import scipy as sp, numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
plt.rc('text', usetex=True)
x = np.arange(-6, 6, 0.1)
distrib_1 = norm(0, 1)
y_distrib_1 = distrib_1.pdf(x)
fig = plt.figure(figsize=(12, 8))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot(x, y_distrib_1, color='red', linewidth=2, label=r'Normal distribution: $\mu = 0, \sigma = 1$')
axes.set_xlabel('x')
axes.set_ylabel('P(x)')
axes.set_title('The Normal Distribution')
axes.grid(True)
axes.legend(loc=2);
plt.show()
现在我要填写x = -1和x = 1之间的范围。我尝试做的是axes.fill_between(x, y_distrib_1, 0, where = -1<x<1)
,但后来我在该行收到错误ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
。
我尝试了axes.fill_between(x, y_distrib_1, 0, where = (-1<x and x<1), color='red')
,但它也无效。
我能做的是:
p = [(True if -1<val and val<1 else False) for val in x]
axes.fill_between(x, y_distrib_1, 0, where = p)
有效,但这段代码感觉很难看。
怎么办?我没有在matplotlib文档中找到任何类似的例子。
答案 0 :(得分:1)
你很亲密,这会奏效:
axes.fill_between(x, y_distrib_1, 0, where = (-1<x) & (x<1))
答案 1 :(得分:-1)
应该是
fill_between(y_distrib_1, 0, where = (-1<x&&x<1)).
请记住,大多数语言都无法解析-1<x<1
之类的内容。尽管这是一个非常合理的数学概念,但大多数代码看到的方式都是这样的:
is -1 < x? Yes? Ok, the statement -1 < x is now TRUE.
is TRUE<1? TRUE in python is 1, so is 1<1, no, FALSE.
代码不会针对-1和1测试x,你必须将其分解并放入“和”(&amp;&amp;)。
编辑:查看使用fill_between的实际方法,看起来你应该这样做
fill_between(y_distrib_1,-1, 1)