【问题标题】:How can I shade an area under a curve between two lines in matplotlib / pandas?如何在 matplotlib/pandas 中两条线之间的曲线下遮蔽区域?
【发布时间】:2016-05-26 19:21:38
【问题描述】:

我正在尝试使用 matplotlib 或多或少地重新创建此图表:

除了我的中心是 100,标准差是 16(像 IQ)。这是我到目前为止所拥有的:

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)

生成这样的正常曲线:

到目前为止一切顺利。但是我不知道如何遮蔽曲线下的区域。

【问题讨论】:

标签: python matplotlib


【解决方案1】:

你可以使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多