【问题标题】:Setting Different error bar colors in bar plot in matplotlib在 matplotlib 的条形图中设置不同的误差线颜色
【发布时间】:2014-03-21 15:43:33
【问题描述】:

关注Setting Different Bar color in matplotlib Python

我想更改错误栏颜色。经过多次尝试,我想出了一个办法:

a = plt.gca()
b = a.bar(range(4), [2]*4, yerr=range(4))
c = a.get_children()[8]
c.set_color(['r','r','b','r'])

有没有更好的方法?当然a.get_children()[8] 根本不是一个通用的解决方案。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    如果您只想将它​​们设置为单一颜色,请使用error_kw kwarg(预计是传递给ax.errorbar 的关键字参数的字典)。

    另外,请注意,您可以将一系列 facecolors 直接传递给 bar,但这不会更改错误栏颜色。

    举个简单的例子:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    ax.bar(range(4), [2] * 4, yerr=range(1, 5), alpha=0.5,
           color=['red', 'green', 'blue', 'cyan', 'magenta'],
           error_kw=dict(ecolor='gray', lw=2, capsize=5, capthick=2))
    ax.margins(0.05)
    
    plt.show()
    

    但是,如果您希望误差条具有不同的颜色,则需要单独绘制它们或在之后对其进行修改。

    如果您使用后一个选项,则实际上不能单独更改 capline 颜色(请注意,在 @falsetru 的示例中它们也没有更改)。例如:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    colors = ['red', 'green', 'blue', 'cyan', 'magenta']
    
    container = ax.bar(range(4), [2] * 4, yerr=range(1, 5), alpha=0.5, color=colors,
           error_kw=dict(lw=2, capsize=5, capthick=2))
    ax.margins(0.05)
    
    connector, caplines, (vertical_lines,) = container.errorbar.lines
    vertical_lines.set_color(colors)
    
    plt.show()
    

    上面答案中的caplines 对象是两个Line2Ds 的元组:一行用于所有顶盖,一行用于所有底盖。如果不删除该艺术家并在其位置创建LineCollection,则无法单独更改帽子的颜色(很容易将它们全部设置为相同的颜色)。

    因此,在这种情况下,您最好单独绘制误差线。

    例如

    import matplotlib.pyplot as plt
    
    x, height, error = range(4), [2] * 4, range(1,5)
    colors = ['red', 'green', 'blue', 'cyan', 'magenta']
    
    fig, ax = plt.subplots()
    ax.bar(x, height, alpha=0.5, color=colors)
    ax.margins(0.05)
    
    for pos, y, err, color in zip(x, height, error, colors):
        ax.errorbar(pos + 0.4, y, err, lw=2, capsize=5, capthick=2, color=color)
    
    plt.show()
    

    【讨论】:

    • 非常非常有帮助,这个信息应该在官方教程中有。
    • 不知什么原因,vertical_lines.set_color(colors) 对我的情节没有影响。
    【解决方案2】:

    也不是一个通用的解决方案,但就是这样。

    a = plt.gca()
    b = a.bar(range(4), [2]*4, yerr=range(4))
    c = b.errorbar.lines[2][b.errorbar.has_xerr] # <----
    c.set_color(['r', 'r', 'b', 'r'])
    
    
    # from matplotlib.collections import LineCollection
    # next(i
    #      for i, x in enumerate(b.errorbar.lines)
    #      if x and any(isinstance(y, LineCollection) for y in x)) == 2
    

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 2023-03-14
      • 2013-09-29
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多