使用PatchCollection在误差图中创建箱型图

在这个例子中,我们通过在x方向和y方向上添加由条形极限定义的矩形块来拼写一个非常标准的误差条形图。为此,我们必须编写自己的自定义函数 make_error_boxes。仔细检查此函数将揭示matplotlib编写函数的首选模式:

  1. an Axes object is passed directly to the function
  2. the function operates on the Axes methods directly, not through the pyplot interface
  3. plotting kwargs that could be abbreviated are spelled out for better code readability in the future (for example we use facecolor instead of fc)
  4. the artists returned by the Axes plotting methods are then returned by the function so that, if desired, their styles can be modified later outside of the function (they are not modified in this example).

创建箱型图示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.collections import PatchCollection
  4. from matplotlib.patches import Rectangle
  5. # Number of data points
  6. n = 5
  7. # Dummy data
  8. np.random.seed(19680801)
  9. x = np.arange(0, n, 1)
  10. y = np.random.rand(n) * 5.
  11. # Dummy errors (above and below)
  12. xerr = np.random.rand(2, n) + 0.1
  13. yerr = np.random.rand(2, n) + 0.2
  14. def make_error_boxes(ax, xdata, ydata, xerror, yerror, facecolor='r',
  15. edgecolor='None', alpha=0.5):
  16. # Create list for all the error patches
  17. errorboxes = []
  18. # Loop over data points; create box from errors at each point
  19. for x, y, xe, ye in zip(xdata, ydata, xerror.T, yerror.T):
  20. rect = Rectangle((x - xe[0], y - ye[0]), xe.sum(), ye.sum())
  21. errorboxes.append(rect)
  22. # Create patch collection with specified colour/alpha
  23. pc = PatchCollection(errorboxes, facecolor=facecolor, alpha=alpha,
  24. edgecolor=edgecolor)
  25. # Add collection to axes
  26. ax.add_collection(pc)
  27. # Plot errorbars
  28. artists = ax.errorbar(xdata, ydata, xerr=xerror, yerr=yerror,
  29. fmt='None', ecolor='k')
  30. return artists
  31. # Create figure and axes
  32. fig, ax = plt.subplots(1)
  33. # Call function to create error boxes
  34. _ = make_error_boxes(ax, x, y, xerr, yerr)
  35. plt.show()

下载这个示例