Matplotlib:调整图例中错误栏的 size/height

Matplotlib: Adjust size/height of errorbars in legend

我想调整错误栏的高度,如 matplotlib 图例所示,以避免它们相互碰撞(如下所示)。

我知道这个 post Matplotlib: Don't show errorbars in legend 讨论了如何删除错误栏,但我不知道如何调整处理程序以使错误栏仍然存在, 只是缩短了。

一个错误栏重叠的工作示例是:

import matplotlib
font = {'family' : 'serif',
    'serif': 'Computer Modern Roman',
    'weight' : 'medium',
    'size'   : 19}
matplotlib.rc('font', **font)
matplotlib.rc('text', usetex=True)

fig,ax1=plt.subplots()  
h0=ax1.errorbar([1,2,3],[1,2,3],[1,2,1],c='b',label='$p=5$')
h1=ax1.errorbar([1,2,3],[3,2,1],[1,1,1],c='g',label='$p=5$')
hh=[h0,h1]
ax1.legend(hh,[H.get_label() for H in hh],bbox_to_anchor=(0.02, 0.9, 1., .102),loc=1,labelspacing=0.01, handlelength=0.14, handletextpad=0.4,frameon=False, fontsize=18.5)

我使用的是 1.5.1 版的 matplotlib,但我认为这不是问题所在。

您可以使用 handler_map kwarg 到 ax.legend 来控制图例句柄。

在这种情况下,您想使用 matplotlib.legend_handler 中的 HandlerErrorbar 处理程序,并设置 xerr_size 选项。默认情况下,这是 0.5,所以我们只需要将该数字减少到适合绘图的值。

根据 the legend guide 的指导,我们可以了解如何使用 handler_map。要仅更改其中一个错误栏句柄,我们可以这样做:

handler_map={h0: HandlerErrorbar(xerr_size=0.3)}

假设您想以相同的方式更改所有错误栏句柄,您可以将 h0 更改为 type(h0):

handler_map={type(h0): HandlerErrorbar(xerr_size=0.3)}

请注意,这只是告诉 handler_map 如何更改所有 Errorbars 的快速方法。请注意,这相当于执行以下操作:

from matplotlib.container import ErrorbarContainer
...
ax1.legend(...
    handler_map={ErrorbarContainer: HandlerErrorbar(xerr_size=0.3)}
    ...)

使用 type(h0) shorthand 意味着您不需要额外导入 ErrorbarContainer.

在您的最小示例中将其放在一起:

import matplotlib
import matplotlib.pyplot as plt

# Import the handler
from matplotlib.legend_handler import HandlerErrorbar

font = {'family' : 'serif',
    'serif': 'Computer Modern Roman',
    'weight' : 'medium',
    'size'   : 19}
matplotlib.rc('font', **font)
matplotlib.rc('text', usetex=True)

fig,ax1=plt.subplots()  
h0=ax1.errorbar([1,2,3],[1,2,3],[1,2,1],c='b',label='$p=5$')
h1=ax1.errorbar([1,2,3],[3,2,1],[1,1,1],c='g',label='$p=5$')
hh=[h0,h1]
ax1.legend(
        hh, [H.get_label() for H in hh],
        handler_map={type(h0): HandlerErrorbar(xerr_size=0.3)},  # adjust xerr_size to suit the plot
        bbox_to_anchor=(0.02, 0.9, 1., .102),
        loc=1, labelspacing=0.01, 
        handlelength=0.14, handletextpad=0.4,
        frameon=False, fontsize=18.5)

plt.show()

为了证明这有效,您可以在我调整误差条大小之前将其与原始图像进行比较: