簡體   English   中英

更改圖例中的標記 matplotlib

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM