【问题标题】:How to create a legend of both color and marker?如何创建颜色和标记的图例?
【发布时间】:2017-07-17 09:18:09
【问题描述】:

我想在图例中同时显示颜色和标记。颜色意味着一件事,而标记意味着另一件事。它应该看起来像附加的图像。这是我当前的代码:

x = np.arange(20)
y = np.sin(x)

fig, ax = plt.subplots()
line1 = ax.scatter(x[:10],y[:10],20, c="red", picker=True, marker='*')
line2 = ax.scatter(x[10:20],y[10:20],20, c="red", picker=True, marker='^')

ia = lambda i: plt.annotate("Annotate {}".format(i), (x[i],y[i]), visible=False)
img_annotations = [ia(i) for i in range(len(x))] 

def show_ROI(event):
    for annot, line in zip([img_annotations[:10],img_annotations[10:20]], [line1, line2]):
        if line.contains(event)[0]:
            ...
    fig.canvas.draw_idle()

fig.canvas.mpl_connect('button_press_event', show_ROI)

plt.show()

【问题讨论】:

  • 你的意思是两个独立的图例吗?
  • @DavidG,它可以是一个图例或两个单独的图例,但标记不是特定于颜色的。标记可以有不同的颜色。而且一种颜色可以有不同的标记。
  • 您能否提供一个示例(最好是图片)来说明预期/期望的结果是什么?
  • @DavidG 我添加了一个我所期望的图像示例。谢谢!
  • link 所写,您可以创建各种图例条目(代理艺术家)。这可能就是你想要的。

标签: python matplotlib legend


【解决方案1】:

以下是一个通用示例,说明如何使用proxy artists 创建具有不同标记和颜色的图例。

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(8,10)
data[:,0] = np.arange(len(data))

markers=["*","^","o"]
colors = ["crimson", "purple", "gold"]


for i in range(data.shape[1]-1):
    plt.plot(data[:,0], data[:,i+1], marker=markers[i%3], color=colors[i//3], ls="none")

f = lambda m,c: plt.plot([],[],marker=m, color=c, ls="none")[0]

handles = [f("s", colors[i]) for i in range(3)]
handles += [f(markers[i], "k") for i in range(3)]

labels = colors + ["star", "triangle", "circle"]

plt.legend(handles, labels, loc=3, framealpha=1)

plt.show()

【讨论】:

    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 2011-09-25
    • 2022-08-19
    • 2021-12-20
    • 2021-01-16
    • 2016-07-13
    • 2019-03-28
    • 1970-01-01
    相关资源
    最近更新 更多