首页 > 解决方案 > 填充颜​​色 Matplotlib

问题描述

我正在尝试填充 matplotlib 中两个密度图之间的区域。该示例模拟 A/B 测试。所以,我想遮蔽由密度图的第一部分组成的区域,从 x = 0.03 到区域 1(或 PDF1)结束。

这是复制的示例代码:

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

a, b = 300, 300
x_a, x_b = 42, 65
rate_a, rate_b = x_a / a, x_b / b

# click_rate = np.linspace(0,0.2, 80)
std_a = np.sqrt(rate_a * (1 - rate_a) / a)
std_b = np.sqrt(rate_b * (1 - rate_b) / b)

z_score = (rate_b - rate_a) / np.sqrt(std_a**2 + std_b**2)
p = norm(rate_b - rate_a, np.sqrt(std_a**2 + std_b**2))

x = np.linspace(-0.05, 0.15, 1000)
x2 = np.linspace(-0.095, 0.075, 1000)

y1 = p.pdf(x)
y2 = p.pdf(x)

fig = plt.figure()

fig, ax1 = plt.subplots()
ax1.plot(x2, y2, label="PDF")
ax1.plot(x, y1, label="PDF")

plt.fill_between(x, 0, y1, where=x>0.03,alpha=0.1, color = 'blue')
plt.fill_between(x, 0, y2, where=x>0.03, label="Prob(b>a)", alpha=0.3, color = 'green')
fig.legend(['PDF1', 'PDF2'])
plt.show()

这是我得到的输出。有人可以帮我调整这个情节吗?抗体

标签: pythonmatplotlib

解决方案


问题是您的 x 值在两个图中都不同。fill_between很优雅,您对两条曲线及其对应的 y 值都有完整的 x 范围。

但是,您可以手动指定它。

plt.fill_between(x,0,y1, np.logical_and((x>0.03),(x<0.0422)),color = 'blue')
plt.fill_between(x2,0,y2,where=x2>0.0422 ,label="Prob(b>a)", color = 'blue')

使用这些你会得到如下输出:

通过查看两条曲线交点的 x 坐标,我得到了幻数 0.0422。要找到这个数字,有一些精确的方法。但是我只是在绘图窗口中查看了光标坐标。


推荐阅读