备注
前往结尾 下载完整示例代码。
fill_between 带透明度#
fill_between 函数在最小和最大边界之间生成一个阴影区域,这对于说明范围非常有用。它有一个非常方便的 where 参数,可以结合填充与逻辑范围,例如,仅在某个阈值以上的曲线上进行填充。
在最基本的层面上,fill_between 可以用来增强图表的视觉效果。让我们比较两张财务数据图表,左边是简单的线图,右边是填充的线图。
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
# load up some sample financial data
r = cbook.get_sample_data('goog.npz')['price_data']
# create two subplots with the shared x and y axes
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
pricemin = r["close"].min()
ax1.plot(r["date"], r["close"], lw=2)
ax2.fill_between(r["date"], pricemin, r["close"], alpha=0.7)
for ax in ax1, ax2:
ax.grid(True)
ax.label_outer()
ax1.set_ylabel('price')
fig.suptitle('Google (GOOG) daily closing price')
fig.autofmt_xdate()

这里不需要 alpha 通道,但它可以用来软化颜色,使图表在视觉上更具吸引力。在其他示例中,如下所示,alpha 通道在功能上很有用,因为阴影区域可以重叠,而 alpha 允许你同时看到两者。请注意,postscript 格式不支持 alpha(这是 postscript 的限制,而不是 matplotlib 的限制),因此在使用 alpha 时,请将图表保存为 PNG、PDF 或 SVG 格式。
我们的下一个示例计算了两个随机游走者群体,它们从具有不同均值和标准差的正态分布中抽取步长。我们使用填充区域来绘制群体平均位置的正负一个标准差。在这里,alpha通道不仅具有美学价值,而且非常实用。
# Fixing random state for reproducibility
np.random.seed(19680801)
Nsteps, Nwalkers = 100, 250
t = np.arange(Nsteps)
# an (Nsteps x Nwalkers) array of random walk steps
S1 = 0.004 + 0.02*np.random.randn(Nsteps, Nwalkers)
S2 = 0.002 + 0.01*np.random.randn(Nsteps, Nwalkers)
# an (Nsteps x Nwalkers) array of random walker positions
X1 = S1.cumsum(axis=0)
X2 = S2.cumsum(axis=0)
# Nsteps length arrays empirical means and standard deviations of both
# populations over time
mu1 = X1.mean(axis=1)
sigma1 = X1.std(axis=1)
mu2 = X2.mean(axis=1)
sigma2 = X2.std(axis=1)
# plot it!
fig, ax = plt.subplots(1)
ax.plot(t, mu1, lw=2, label='mean population 1')
ax.plot(t, mu2, lw=2, label='mean population 2')
ax.fill_between(t, mu1+sigma1, mu1-sigma1, facecolor='C0', alpha=0.4)
ax.fill_between(t, mu2+sigma2, mu2-sigma2, facecolor='C1', alpha=0.4)
ax.set_title(r'random walkers empirical $\mu$ and $\pm \sigma$ interval')
ax.legend(loc='upper left')
ax.set_xlabel('num steps')
ax.set_ylabel('position')
ax.grid()

where 关键字参数在突出显示图表的某些区域时非常方便。where 接受一个布尔掩码,其长度与 x、ymin 和 ymax 参数相同,并且仅在布尔掩码为 True 的区域填充。在下面的示例中,我们模拟了一个随机行走者,并计算了群体位置的分析均值和标准差。群体均值以虚线显示,均值加减一个标准差以填充区域显示。我们使用 where 掩码 X > upper_bound 来找到行走者超出一个标准差边界的区域,并将该区域涂成红色。
# Fixing random state for reproducibility
np.random.seed(1)
Nsteps = 500
t = np.arange(Nsteps)
mu = 0.002
sigma = 0.01
# the steps and position
S = mu + sigma*np.random.randn(Nsteps)
X = S.cumsum()
# the 1 sigma upper and lower analytic population bounds
lower_bound = mu*t - sigma*np.sqrt(t)
upper_bound = mu*t + sigma*np.sqrt(t)
fig, ax = plt.subplots(1)
ax.plot(t, X, lw=2, label='walker position')
ax.plot(t, mu*t, lw=1, label='population mean', color='C0', ls='--')
ax.fill_between(t, lower_bound, upper_bound, facecolor='C0', alpha=0.4,
label='1 sigma range')
ax.legend(loc='upper left')
# here we use the where argument to only fill the region where the
# walker is above the population 1 sigma boundary
ax.fill_between(t, upper_bound, X, where=X > upper_bound, fc='red', alpha=0.4)
ax.fill_between(t, lower_bound, X, where=X < lower_bound, fc='red', alpha=0.4)
ax.set_xlabel('num steps')
ax.set_ylabel('position')
ax.grid()

填充区域的另一个方便用途是突出显示 Axes 的水平或垂直跨度——为此,Matplotlib 提供了辅助函数 axhspan 和 axvspan。请参阅 绘制跨越一个轴的区域。
plt.show()