如何在plot legend中显示文本标签?(例如,删除图例中的标签行)

2024-06-11 20:00:21 发布

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

我想在图例中显示一行标签的文本,但不想显示一行(如下图所示):

enter image description here

我试图最小化图例的行和标签,并且只覆盖新的标签(如下面的代码所示)。然而,传说把两者都带回来了。

    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')

Tags: 代码in文本falseforget标签ax
1条回答
网友
1楼 · 发布于 2024-06-11 20:00:21

您可以通过^{}在图例中设置handletextpadhandlelength,如下所示:

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的详细信息,请参阅文档(linked here,复制如下):

handletextpad : float or None

The pad between the legend handle and text. Measured in font-size units. Default is None, which will take the value from rcParams["legend.handletextpad"].

handlelength : float or None

The length of the legend handles. Measured in font-size units. Default is None, which will take the value from rcParams["legend.handlelength"].

使用上述代码:

enter image description here

有了几行额外的标签可以有相同的颜色作为他们的行。只需通过legend.get_texts()使用.set_color()

# 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] )

enter image description here

只要调用plt.legend()就可以得到:

enter image description here

网友
2楼 · 发布于 2024-06-11 20:00:21

在这一点上,可以说只使用^{}更容易。

例如:

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()

enter image description here

但是,如果您确实想使用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()

enter image description here

网友
3楼 · 发布于 2024-06-11 20:00:21

我找到了另一个更简单的解决方案-只需在图例属性中将标记的比例设置为零:

plt.legend(markerscale=0)

这在散点图中特别有用,因为您不希望标记在视觉上被误认为是真正的数据点(甚至是异常点!)。

相关问题 更多 >