How to fill the region between density plots

Question:

I am trying to fill in the region between two density plots in matplotlib. The example simulates an A/B testing. So, I want to shade region that consist of the first part of the density plot starting from x = 0.03 till the end of region 1 (or PDF1).

Here is an example code for replication:

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()

And here is the output I am getting. Can someone please help me tweak this plot?

ab

Asked By: G1124E

||

Answers:

The problem is your x-values differ in both graphs. fill_between is elegant you have the full range of x for both curves and their corresponding y values.

You can however specify it manually.

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')

Using these you would get output like:

I got the magic number 0.0422 by looking at x-coordinate of the intersection of the two curves. To find this number there are some precise ways. However I just looked at cursor coordinates in the plot window.

Answered By: Rishabh Kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.