[英]Change marker in the legend in matplotlib
假设你 plot 一组数据:
plt.plot(x,y, marker='.', label='something')
plt.legend()
在显示屏上,您将获得. something
. something
,但是您如何将其更改为- something
,以便出现在图例中的标记是一条线而不是一个点?
解决方案肯定取决于您要转换标记的标准。 手动执行此操作很简单:
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()
以自动方式执行相同操作,即图中的每条线都有对应的图例句柄,这是一条相同颜色的线,但没有标记:
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()
跟进更多信息。 如果您想在使用
plt.scatter()<\/code>时使图例中的标记更加明显,您可以执行以下操作来自动化标记更改过程。
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(), ...)
它适用于 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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.