繁体   English   中英

matplotlib中填充的误差线(矩形)

[英]Filled errorbars in matplotlib (rectangles)

是否可以在matplotlib中绘制这样的图? 我只关心红色填充的矩形,可以使用errorbar轻松完成errorbar

例

不幸的是, errorbar无法做到这一点,但是您可以根据自己的错误数据创建一个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
x=np.arange(0,n,1)
y=np.random.rand(n)*5.

# Dummy errors (above and below)
xerr=np.random.rand(2,n)
yerr=np.random.rand(2,n)

# Create figure and axes
fig,ax = plt.subplots(1)

# Plot data points
ax.errorbar(x,y,xerr=xerr,yerr=yerr,fmt='None',ecolor='k')

# Function to plot error boxes
def makeErrorBoxes(xdata,ydata,xerror,yerror,fc='r',ec='None',alpha=0.5):

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

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

    # Create patch collection with specified colour/alpha
    pc = PatchCollection(errorboxes,facecolor=fc,alpha=alpha,edgecolor=ec)

    # Add collection to axes
    ax.add_collection(pc)

# Call function to create error boxes
makeErrorBoxes(x,y,xerr,yerr)

# Add some space around the data points on the axes
ax.margins(0.1)

plt.show()

在此处输入图片说明

使用matplotlib.patches确实很容易绘制正方形,例如:

import matplotlib.pyplot as pl
import matplotlib.patches

pl.figure()
ax = pl.gca()
ax.add_patch(
   matplotlib.patches.Rectangle(
       (1.0, 1.0), # x, y
       2.0,        # width
       2.0,        # height
       color='r', alpha=0.5
   ) )
ax.set_aspect(1)

pl.xlim(0,4)
pl.ylim(0,4)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM