首页 > 解决方案 > 图例中的多行(具有不同标记)

问题描述

我想在图例中显示具有相同标签但不同标记的多行。

我要绘制的图表与此类似:

阴谋

但是没有标记设置LineCollection,我希望每行都有不同的标记。

任何想法?谢谢你。

标签: pythonmatplotlib

解决方案


您展示的图片源于图例演示。与那里所做的类似,您可以将图例处理程序子类化以创建选择的图例。

这里可以使用 HandlerTuple 以便可以直接提供图例中的完整行列表。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple


class HandlerLinesVertical(HandlerTuple):
    def create_artists(self, legend, orig_handle,
                   xdescent, ydescent, width, height, fontsize,
                   trans):
        ndivide = len(orig_handle)
        a_list = []
        for i, handle in enumerate(orig_handle):
            y = (height / float(ndivide)) * i -ydescent
            line = plt.Line2D(np.array([0,1])*width, [-y,-y])
            line.update_from(handle)
            line.set_marker(None)
            point = plt.Line2D(np.array([.5])*width, [-y])
            point.update_from(handle)
            for artist in [line, point]:
                artist.set_transform(trans)
            a_list.extend([line,point])
        return a_list

x = np.linspace(0, 5, 15)

fig, ax = plt.subplots()

markers = ["o", "s", "d", "+", "*"]
lines = []
for i, marker in zip(range(5),markers):
    line, = ax.plot(x, np.sin(x) - .1 * i, marker=marker)
    lines.append(line)

ax.legend([tuple(lines)], ["legend entry"], handler_map={tuple:HandlerLinesVertical()},
           handleheight=8 )
plt.show()

在此处输入图像描述


推荐阅读