Python中Matplotlib的完全自定义图例

Jon*_*nny 7 python plot matplotlib

我使用Matplotlib基本上绘制'图片',而不是绘制数据.

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

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

有没有一种方法来定义自定义handleslabels,其中handles必须是字母数字字母代替正常的标志像'*''o'.

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

Joe*_*ton 13

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

作为一个例子(其中大部分是相对"花哨"的调用annotate):

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述