python - matplotlib 函数图的彩色部分

标签 python matplotlib polygon

我想知道是否有一种更优雅的方法来在下面的代码中绘制多边形,或者使用特殊的绘图函数或参数?

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
x = np.linspace(-4,4,150)
# plot density with shaded area showing Pr(-2 <= x <= 1)
lb = -2
ub = 1
d=norm.pdf(x)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, d)
### can this be done more elegantly ###
sx = np.linespace(lb,ub,100)
sd = norm.pdf(sx)
sx = [lb] + sx + [ub]
sd = [0] + list(sd) + [0]
xy = np.transpose(np.array([sx, sd]))
pgon = plt.Polygon(xy, color='b')
#######################################
ax.add_patch(pgon)
plt.show()

最佳答案

也许您正在寻找 plt.fill_between :

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
x = np.linspace(-4,4,150)
# plot density with shaded area showing Pr(-2 <= x <= 1)
lb = -2
ub = 1
d = norm.pdf(x)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, d)

idx = np.searchsorted(x,[lb,ub])
sx = x[idx[0]:idx[1]]
sd = d[idx[0]:idx[1]]
plt.fill_between(sx, sd, 0, color = 'b')
plt.show()

enter image description here

关于python - matplotlib 函数图的彩色部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14261988/

相关文章:

python - 用户如何使用 shell 与我的 python 脚本通信?

objective-c - UIView drawRect() : fill everything except polygon

MongoDB : Check if a point is inside a stored polygon

python - 将可旋转的 3D 绘图从 Python 导出到 HTML

python - 在 Python (Matplotlib) 中重用模块引用

python - 导入 matplotlib 和 matplotlib.pyplot 有什么区别?

java - 创建图像不透明部分的多边形

javascript - 解码 Node.js 中用 Python 编码的字符串

python - 如何在 python 中从游标中删除和返回值

python - 如何进行prefetch_相关?我做错了吗?