簡體   English   中英

你如何在情節圖例中顯示文本標簽? (例如刪除圖例中的標簽行)

[英]How do you just show the text label in plot legend? (e.g. remove a label's line in the legend)

我想在圖例中顯示一行標簽的文本,但不是一行(如下圖所示):

在此處輸入圖片說明

我試圖最小化圖例的線條和標簽,並且也只覆蓋新標簽(如下面的代碼所示)。 然而,這個傳說把兩者都帶回來了。

    legend = ax.legend(loc=0, shadow=False) 
    for label in legend.get_lines(): 
        label.set_linewidth(0.0) 
    for label in legend.get_texts(): 
        label.set_fontsize(0) 

    ax.legend(loc=0, title='New Title')

在這一點上,可以說只使用annotate更容易。

例如:

import numpy as np
import matplotlib.pyplot as plt

data = np.random.normal(0, 1, 1000).cumsum()

fig, ax = plt.subplots()
ax.plot(data)
ax.annotate('Label', xy=(-12, -12), xycoords='axes points',
            size=14, ha='right', va='top',
            bbox=dict(boxstyle='round', fc='w'))
plt.show()

在此處輸入圖片說明

但是,如果您確實想使用legend ,那么您可以這樣做。 除了將它們的大小設置為 0 並刪除它們的填充之外,您還需要顯式隱藏圖例手柄。

import numpy as np
import matplotlib.pyplot as plt

data = np.random.normal(0, 1, 1000).cumsum()

fig, ax = plt.subplots()
ax.plot(data, label='Label')

leg = ax.legend(handlelength=0, handletextpad=0, fancybox=True)
for item in leg.legendHandles:
    item.set_visible(False)
plt.show()

在此處輸入圖片說明

你可以只設置handletextpadhandlelength在通過圖例legend_handler如下圖所示:

import matplotlib.pyplot as plt
import numpy as np
# Plot up a generic set of lines
x = np.arange( 3 )
for i in x:
    plt.plot( i*x, x, label='label'+str(i), lw=5 )
# Add a legend 
# (with a negative gap between line and text, and set "handle" (line) length to 0)
legend = plt.legend(handletextpad=-2.0, handlelength=0)

有關詳細信息handletextpadhandlelength是在文檔(鏈接在這里,與下面復制):

handletextpad : 浮動或無

圖例句柄和文本之間的襯墊。 以字體大小單位測量。 默認值為 None,它將從 rcParams[ "legend.handletextpad" ] 中獲取值。

句柄長度:浮動或無

圖例手柄的長度。 以字體大小單位測量。 默認值為 None,它將從 rcParams["legend.handlelength"] 中獲取值。

用上面的代碼:

在此處輸入圖片說明

使用一些額外的線條,標簽可以與它們的線條具有相同的顏色。 只需通過.set_color()使用legend.get_texts()

# Now color the legend labels the same as the lines
color_l = ['blue', 'orange', 'green']
for n, text in enumerate( legend.texts ):
    print( n, text)
    text.set_color( color_l[n] )

在此處輸入圖片說明

只需調用plt.legend()

在此處輸入圖片說明

我找到了另一個更簡單的解決方案 - 只需在圖例屬性中將標記的比例設置為零:

plt.legend(markerscale=0)

這在散點圖中特別有用,當您不希望標記在視覺上被誤認為是真實數據點(甚至異常值!)。

建議最佳答案: ax.legend(handlelength=0) handlelength=0 ,例如: ax.legend(handlelength=0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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