在Matplotlib中更改图例中的标记符号

11

假设你要绘制一组数据:

plt.plot(x,y, marker='.', label='something')
plt.legend()
在显示屏上,你会得到 . something ,但是你要如何将它更改为 - something ,以便出现在图例中的标记是一条线而不是一个点?
3个回答

9
这个解决方案肯定取决于你想要转换标记的标准。手动完成这个过程很简单:
import matplotlib.pyplot as plt

line, = plt.plot([1,3,2], marker='o', label='something')
plt.legend(handles = [plt.plot([],ls="-", color=line.get_color())[0]],
           labels=[line.get_label()])

plt.show()

enter image description here

在自动化方式下执行相同操作,即每条绘图线都有其对应的图例句柄,该句柄是一条没有标记但颜色相同的线:
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D

plt.plot([1,3,2], marker='o', label='something')
plt.plot([2,3,3], marker='o', label='something else')

def update_prop(handle, orig):
    handle.update_from(orig)
    handle.set_marker("")

plt.legend(handler_map={plt.Line2D:HandlerLine2D(update_func=update_prop)})

plt.show()

enter image description here


散点图的等效物是什么? - DataMan

0

对于3D图,它的工作方式略有不同:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

ax = plt.gca()
handles, labels =  ax.get_legend_handles_labels()
updated_handles = []

for handle in handles:              
   updated_handles.append(mpatches.Patch(                                  
   color=handle.get_markerfacecolor(),                                 
   label=handle.get_label()))
                     
by_label = dict(sorted(dict(zip(labels,
                updated_handles)).items()))
                            
ax.legend(by_label.values(), by_label.keys())

0

为了提供更多信息。如果您想在使用plt.scatter()时使图例中的标记更加可见,您可以执行以下操作来自动化标记更改过程。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

handles, labels, plt.gca().get_legend_handles_labels()
updated_handles = []
for handle in handles:
  updated_handles.append(mpatches.Patch(color=handle.get_facecolor(), label=handle.get_label()))
by_label = dict(sorted(dict(zip(all_labels, updated_handles)).items()))
plt.figlegend(by_label.values(), by_label.keys(), ...)

如果您想使用特定的坐标轴,请将plt.gca()更改为您自己的。另外,在第8行,我对图例进行了排序,这是您可以选择不做的事情。

handles,labels = plt.gca().get_legend_handles_labels() - msch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接