python - 填充颜色 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()
解决方案
问题是您的 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。要找到这个数字,有一些精确的方法。但是我只是在绘图窗口中查看了光标坐标。
推荐阅读
- reactjs - React 页面不会加载映射的元素,直到再次调用它们
- javascript - JS正则表达式匹配字符串中以空格分隔的单词
- javascript - 添加项目时如何在每行中保持相同数量的 flex 子项
- c# - 根据返回的状态码将 JSON 对象反序列化为字符串或具体类型
- reactjs - 在每个页面中显示 PageNotFound 组件。反应
- sql - 在 SELECT 语句的结果中添加任意列
- html - Bootstrap col-4 类占用容器的全宽问题
- google-colaboratory - 无法在 Colab Pro 中使用 GPU P100
- python - python findall 函数的正确模式是什么?
- algorithm - 矩阵中行进收集的最大硬币