【问题标题】:Filled errorbars in matplotlib (rectangles)matplotlib 中的填充误差线(矩形)
【发布时间】:2018-01-22 02:28:14
【问题描述】:

是否可以在 matplotlib 中制作这样的情节?我只关心红色填充的矩形,使用errorbar 可以轻松完成交叉。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    很遗憾,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()
    

    【讨论】:

    • @tcaswell:当然。我想我已经做到了(examples/statistics),但我是 git 新手,所以如果我做错了什么,请告诉我:)
    【解决方案2】:

    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)
    

    【讨论】:

    • 画一个正方形真的很容易......我希望有一个更简单的方法所以对errorbar说:“画矩形”
    • 啊,这样。对不起,我误解了你的问题
    • 那我可能会为pl.errorbar写一个小包装函数来自动化错误栏+矩形的组合
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多