备注
前往结尾 下载完整示例代码。
使用 PatchCollection 从误差条创建框#
在这个例子中,我们通过添加一个由x和y方向的条形图限制定义的矩形补丁,来美化一个相当标准的误差条形图。为此,我们必须编写一个名为 make_error_boxes 的自定义函数。仔细检查这个函数将揭示在matplotlib中编写函数的推荐模式:
一个
Axes对象直接传递给函数该函数直接操作
Axes方法,而不是通过pyplot接口。可以缩写的绘图关键字参数被完整拼写,以提高未来代码的可读性(例如,我们使用 facecolor 而不是 fc)
Axes绘图方法返回的艺术家随后由函数返回,以便在需要时,可以在函数外部修改它们的样式(在此示例中未进行修改)。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
# Number of data points
n = 5
# Dummy data
np.random.seed(19680801)
x = np.arange(0, n, 1)
y = np.random.rand(n) * 5.
# Dummy errors (above and below)
xerr = np.random.rand(2, n) + 0.1
yerr = np.random.rand(2, n) + 0.2
def make_error_boxes(ax, xdata, ydata, xerror, yerror, facecolor='r',
edgecolor='none', alpha=0.5):
# Loop over data points; create box from errors at each point
errorboxes = [Rectangle((x - xe[0], y - ye[0]), xe.sum(), ye.sum())
for x, y, xe, ye in zip(xdata, ydata, xerror.T, yerror.T)]
# Create patch collection with specified colour/alpha
pc = PatchCollection(errorboxes, facecolor=facecolor, alpha=alpha,
edgecolor=edgecolor)
# Add collection to Axes
ax.add_collection(pc)
# Plot errorbars
artists = ax.errorbar(xdata, ydata, xerr=xerror, yerr=yerror,
fmt='none', ecolor='k')
return artists
# Create figure and Axes
fig, ax = plt.subplots(1)
# Call function to create error boxes
_ = make_error_boxes(ax, x, y, xerr, yerr)
plt.show()

参考文献
以下示例展示了以下函数、方法、类和模块的使用: