如何在matplotlib / pandas中的两条线之间的曲线下遮挡区域?

时间:2016-05-26 19:21:39

标签: python matplotlib

我正在尝试使用matplotlib:

或多或少地重新创建此图表

enter image description here

除了我的中心是100,标准差是16(如智商)。这就是我到目前为止所做的:

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats as stats
x = np.linspace(50,150,100)
iq = stats.norm.pdf(x, 100, 16)
plt.plot(x,iq)

这会生成如下的正常曲线:

enter image description here

到目前为止一切顺利。但我对如何遮蔽曲线下的区域感到茫然。

1 个答案:

答案 0 :(得分:7)

您可以使用plt.fill_between

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

plt.style.use('ggplot')

mean = 100
std = 16

x = np.linspace(mean - 5 * std, mean + 5 * std, 1000)

iq = stats.norm(mean, std)

plt.plot(x, iq.pdf(x), 'r-', lw=3)

colors = ['c', 'r', 'b', 'g', ]
colors = colors + list(reversed(colors))

for i, color in zip(range(-4, 4), colors):
    low = mean + i * std
    high = mean + (i + 1) * std
    px = x[np.logical_and(x >= low, x <= high)]
    plt.fill_between(
        px,
        iq.pdf(px),
        color=color,
        alpha=0.5,
        linewidth=0,
    )

plt.tight_layout()
plt.savefig('test.png', dpi=300)

result