Matplotlib 仅填充两个 x 值之间曲线下的区域 [英] Matplotlib fill area under curve between two x values only

查看:60
本文介绍了Matplotlib 仅填充两个 x 值之间曲线下的区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想填充水平轴上两个值之间的某个曲线下的区域.我尝试过

I'd like to fill the area under some curve between two values on the horizontal axis only. I tried

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm

x = np.linspace(-4,4, 10000)
nVals = [norm.pdf(i,0,1) for i in x]

line = plt.plot(x,nVals)

plt.fill_between(x,nVals,color = '#111111',where = x > -3 and x < -2)
plt.axis([-4,4,0,.5])
plt.show()

但它返回

ValueError:包含多个元素的数组的真值不明确.使用a.any()或a.all()

我听不懂这条消息;当我跑步时

I don't understand this message; when I run

z = -2.5
print z > -3 and z < -2

Python 确实理解我的意思并打印

Python does understand what I mean and prints

那为什么在 fill_between 上不起作用,我该如何解决呢?

So why doesn't this work with fill_between and how can I solve that?

推荐答案

发生此错误的原因

x > -3 and x < -2

是一个模棱两可的 numpy 表达式,因此会引发错误.相反,您想要

is an ambiguous numpy expression, so it raises the error. Instead you want

(x > -3) & (x < -2)

其他选项是使用 logical_and bitwise_and (甚至 * 应该可以工作).

Other options are to use logical_and or bitwise_and (or even * should work).

这篇关于Matplotlib 仅填充两个 x 值之间曲线下的区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆