Ibe
Ibe

Reputation: 6035

Reproduce two distributions as provided on a single plot using Python

I want to draw distributions like shown in figure below -- tail of distributions. I have tried following but not quite getting there:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math

mean1 = 0
variance1 = 1
sigma1 = math.sqrt(variance1)
x = np.linspace(-3,3.5,100, endpoint=True)
plt.plot(x,mlab.normpdf(x,mean1,sigma1))

mean2 = 0.4
variance2 = 2
sigma2 = math.sqrt(variance2)
y = np.linspace(-4,3.5,100, endpoint=False)
plt.plot(x,mlab.normpdf(y,mean2,sigma2))
##plt.axis('off')
plt.yticks([])
plt.xticks([])
plt.show()

Any suggestions would be appreciative?

enter image description here

Upvotes: 0

Views: 181

Answers (1)

cphlewis
cphlewis

Reputation: 16249

You want fill_between:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math

mean1 = 0
variance1 = 1
sigma1 = math.sqrt(variance1)
x = np.linspace(-3,3.5,100, endpoint=True)
y1 = mlab.normpdf(x,mean1,sigma1)
fig, ax = plt.subplots()
ax.plot(x,y1)

mean2 = 0.4
variance2 = 2
sigma2 = math.sqrt(variance2)
y = np.linspace(-4,3.5,100, endpoint=False)
y2 = mlab.normpdf(y,mean2,sigma2)
ax.plot(x,y2)


ax.fill_between(x[:30], y1[:30], color='blue')
ax.fill_between(x[:30], y2[:30], color='green')
ax.fill_between(x[-30:], y1[-30:], y2[-30:], color='red', alpha=0.5)
ax.set_yticks([])
ax.set_xticks([])
plt.savefig('fill_norms.png')
plt.show()

enter image description here

This is a crazy simple example -- see the cookbook examples and look at the where clause; your fill-between highlights can adapt to changes in the lines you're plotting (e.g., an automatic red fill_between everywhere BADTHING exceeds GOODTHING, without your having to figure out the index (30 or -30 in this example)).

Upvotes: 3

Related Questions