使用 PatchCollection 从误差棒创建方框#

在此示例中,我们通过添加一个矩形补丁来美化一个相当标准的误差棒图,该矩形补丁由误差棒在 x 和 y 方向上的限制定义。为此,我们必须编写自己的自定义函数 make_error_boxes。仔细检查此函数将揭示编写 matplotlib 函数的首选模式:

  1. Axes 对象直接传递给函数

  2. 函数直接操作 Axes 方法,而不是通过 pyplot 接口

  3. 可缩写的绘图关键字参数被完整写出,以提高将来的代码可读性(例如,我们使用 facecolor 而不是 fc

  4. 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()
errorbars and boxes

标签:图表类型: 误差棒 组件: 矩形 组件: PatchCollection 领域: 统计

由 Sphinx-Gallery 生成的画廊