我可以使用 matplotlib 制作图例显示箱线图吗?

Can I make a plot legend show box plots using matplotlib?

我正在使用一种非常规的方法使用箱形图来传达数据;然而,该图显示的是箱形图而不是分布图并不是很明显。因此,我想让情节图例显示小的颜色编码的箱形图(现在它显示线条)。有办法吗?

我目前正在使用通过创建多个 Line2D 对象制作的自定义图例。我喜欢用小箱形图而不是线条制作自定义图例的方法。

基于 and ,我创建了一个绘制箱线图的图例处理程序。它的颜色来自 Line2D 艺术家,这可能适合也可能不适合,具体取决于您的用例。

from matplotlib.legend_handler import HandlerBase

class HandlerBoxPlot(HandlerBase):
    def create_artists(self, legend, orig_handle,
                   xdescent, ydescent, width, height, fontsize,
                   trans):
        a_list = []
        a_list.append(matplotlib.lines.Line2D(np.array([0, 0, 1, 1, 0])*width-xdescent, 
                                              np.array([0.25, 0.75, 0.75, 0.25, 0.25])*height-ydescent)) # box

        a_list.append(matplotlib.lines.Line2D(np.array([0.5,0.5])*width-xdescent,
                                              np.array([0.75,1])*height-ydescent)) # top vert line

        a_list.append(matplotlib.lines.Line2D(np.array([0.5,0.5])*width-xdescent,
                                              np.array([0.25,0])*height-ydescent)) # bottom vert line

        a_list.append(matplotlib.lines.Line2D(np.array([0.25,0.75])*width-xdescent,
                                              np.array([1,1])*height-ydescent)) # top whisker

        a_list.append(matplotlib.lines.Line2D(np.array([0.25,0.75])*width-xdescent,
                                              np.array([0,0])*height-ydescent)) # bottom whisker

        a_list.append(matplotlib.lines.Line2D(np.array([0,1])*width-xdescent,
                                              np.array([0.5,0.5])*height-ydescent, lw=2)) # median
        for a in a_list:
            a.set_color(orig_handle.get_color())
        return a_list

fig, ax = plt.subplots()

l1, = ax.plot([0,1],[0,1],c='C0')
l2, = ax.plot([1,0],[0,1],c='C1')

ax.legend([l1,l2], ["legend 1", "legend 2"], handler_map={l1:HandlerBoxPlot(), l2:HandlerBoxPlot()}, handleheight=3)