【问题标题】:Completely custom legend in Matplotlib, PythonMatplotlib、Python 中完全自定义的图例
【发布时间】:2015-04-28 15:53:29
【问题描述】:

我使用 Matplotlib 基本上是为了绘制“图片”,而不是用于绘制数据。

在“图片”中,我使用plt.annotate 标记图片的某些部分。

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

有没有办法定义自定义handleslabels,其中handles 必须是字母数字字母,而不是像'*''o' 这样的普通标记。

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

【问题讨论】:

  • 您可以定义自己的图例键。看看this answer
  • 谢谢,但该答案解释了如何使用不同的形状作为图例键。我不确定如何使用该答案实现字母数字字母。

标签: python matplotlib plot


【解决方案1】:

有很多方法可以做到这一点,但在这种情况下使用代理艺术家可能是最简单的。您可以使用任意文本作为标记,因此很容易伪造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()

【讨论】:

  • 太棒了!感谢您的回答。
【解决方案2】:

在大多数情况下,您可能还想在自定义图例中用颜色说明图形上的元素。在这种情况下,我会简单地使用 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多