Matplotlib is hiring a Research Software Engineering Fellow! See discourse for details. Apply by January 3, 2020

Version 3.1.1
matplotlib
Fork me on GitHub

目录

Related Topics

使用PatchCollection从错误栏创建框

在本例中,我们通过添加一个矩形补片(由x和y方向上的条限制定义)来快速绘制一个相当标准的误差线图。为此,我们必须编写自己的自定义函数 make_error_boxes . 仔细检查此功能将显示Matplotlib的首选书写模式:

  1. 一个 Axes 对象直接传递给函数
  2. 该功能在 Axes 方法直接,而不是通过 pyplot 界面
  3. 为了将来更好的代码可读性(例如,我们使用 facecolor 而不是 fc )
  4. 艺术家们由 Axes 然后,函数返回打印方法,这样,如果需要,可以稍后在函数外部修改它们的样式(在本例中不修改)。
使用PatchCollection从错误栏创建框
import numpy as np
import matplotlib.pyplot as plt
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):

    # Create list for all the error patches
    errorboxes = []

    # Loop over data points; create box from errors at each point
    for x, y, xe, ye in zip(xdata, ydata, xerror.T, yerror.T):
        rect = Rectangle((x - xe[0], y - ye[0]), xe.sum(), ye.sum())
        errorboxes.append(rect)

    # 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()