在 Matplotlib 中完全自定义图例,Python

Completely custom legend in Matplotlib, Python

我使用 Matplotlib 主要是画一个 'picture',而不是用来绘制数据。

在'picture'中我用plt.annotate来标记图片的某些部分。

我现在想制作一个完全自定义的图例来指示符号的含义。

有没有办法定义自定义 handleslabels,其中 handles 必须是字母数字字母而不是像 '*' 或 [=16 这样的普通标记=].

这可能还是我必须使用 plt.annotation 手动构建图例?

有很多方法可以做到这一点,但在这种情况下使用代理艺术家可能是最简单的方法。您可以使用任意文本作为标记,因此很容易使用假 Line2D 的显示标签而不是行。

举个例子(其中大部分是对 annotate 的相对 "fancy" 调用):

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

def main():
    labels = ['A', 'B', 'C']
    positions = [(2, 5), (1, 1), (4, 8)]
    descriptions = ['Happy Cow', 'Sad Horse', 'Drooling Dog']

    # Plot the data, similar to what you described...
    fig, ax = plt.subplots()
    ax.imshow(np.random.random((10, 10)), interpolation='none')
    for label, xy in zip(labels, positions):
        ax.annotate(label, xy, xytext=(20, 20), size=15,
                    textcoords='offset points',
                    bbox={'facecolor':'white'},
                    arrowprops={'arrowstyle':'->'})

    # Create a legend with only labels
    proxies = [create_proxy(item) for item in labels]
    ax.legend(proxies, descriptions, numpoints=1, markerscale=2)

    plt.show()

def create_proxy(label):
    line = matplotlib.lines.Line2D([0], [0], linestyle='none', mfc='black',
                mec='none', marker=r'$\mathregular{{{}}}$'.format(label))
    return line

main()

在大多数情况下,您可能还想在自定义图例中用颜色说明图形上的元素。在这种情况下我会简单地使用 matplotlib 自己的函数,而不是你也不需要编写自己的复杂函数。

import matplotlib 

red_line = matplotlib.lines.Line2D([], [], color='red',markersize=100, label='Blue line')


blue_line = matplotlib.lines.Line2D([], [], color='blue', markersize=100, label='Green line')
purple_line = matplotlib.lines.Line2D([], [], color='purple', markersize=100, label='Green line')

handles = [blue_line,red_line, purple_line]
labels = [h.get_label() for h in handles] 

ax.legend(handles=handles, labels=labels)  
plt.show()