Matplotlib:从头开始创建彩色标记图例

2024-05-15 16:46:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在Matplotlib中,我试图用像这样的彩色“标记”创建一个传奇:

Markers legend

这个是用scatter函数做的,但不适合我的情节。我想“从头开始”制作一个图例,没有相关数据。 颜色很重要,因此应该是每个标记的属性。

我试过了

import matplotlib.markers as mmark
list_mak = [mmark.MarkerStyle('.'),mmark.MarkerStyle(','),mmark.MarkerStyle('o')]
list_lab = ['Marker 1','Marker 2','Marker 3']

plt.legend(list_mak,list_lab)

但是:

1)类不支持颜色信息

2)我得到警告:

UserWarning: Legend does not support <matplotlib.markers.MarkerStyle object at 0x7fca640c44d0> instances.
A proxy artist may be used instead.

但是我如何定义一个基于标记的代理艺术家呢?

谢谢你的帮助!


Tags: 标记matplotlib颜色labmarkerlist传奇彩色
2条回答

按照legend guide中给出的示例,可以使用^{}对象而不是marker对象。

与指南中给出的示例的唯一区别是您希望设置linestyle='None'

import matplotlib.lines as mlines
import matplotlib.pyplot as plt

blue_star = mlines.Line2D([], [], color='blue', marker='*', linestyle='None',
                          markersize=10, label='Blue stars')
red_square = mlines.Line2D([], [], color='red', marker='s', linestyle='None',
                          markersize=10, label='Red squares')
purple_triangle = mlines.Line2D([], [], color='purple', marker='^', linestyle='None',
                          markersize=10, label='Purple triangles')

plt.legend(handles=[blue_star, red_square, purple_triangle])

plt.show()

enter image description here

您可以将HandlerBase子类化,以便从(color, marker)元组创建处理程序。

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerBase

list_color  = ["c", "gold", "crimson"]
list_mak    = ["d","s","o"]
list_lab    = ['Marker 1','Marker 2','Marker 3']

ax = plt.gca()

class MarkerHandler(HandlerBase):
    def create_artists(self, legend, tup,xdescent, ydescent,
                        width, height, fontsize,trans):
        return [plt.Line2D([width/2], [height/2.],ls="",
                       marker=tup[1],color=tup[0], transform=trans)]


ax.legend(list(zip(list_color,list_mak)), list_lab, 
          handler_map={tuple:MarkerHandler()}) 

plt.show()

enter image description here

相关问题 更多 >