python - 如何创建颜色和标记的图例?

标签 python matplotlib legend

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

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()

enter image description here

最佳答案

以下是如何使用 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()

enter image description here

关于python - 如何创建颜色和标记的图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45140295/

相关文章:

Python:定义具有可变数量参数的函数

python - 在嵌套字典中移动字典

r - 更改主题后 ggpairs 中的自定义图例消失

Python:动态运行文件夹中所有Python脚本中的所有函数

python - Pandas 、numpy.where() 和 numpy.nan

python - 您将如何在 Python 中绘制此 3D 可视化图?

python - 如何在中心绘制子图并使颜色条与其中一个子图的长度相同?

python - matplotlib:以 None 作为值绘制 numpy 数组

python - matplotlib 中的 Latex 脚本

python - 全局图例和标题旁的次要情节