Matplotlib:删除行“破折号".并且仅在图例中显示文本 [英] Matplotlib: Remove line "dashes" and only display text in legend

查看:98
本文介绍了Matplotlib:删除行“破折号".并且仅在图例中显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建了图例并根据需要设置了文本格式,但无法弄清楚如何删除破折号"行,从而仅显示文本.这就是我现在要得到的(注意行如何通过右对齐的文本):

Created a legend and formatted the text as needed, but can't figure out how to remove the line "dashes" so that only text appears. Here's what I'm getting now (notice how the line is going through the text that is being right aligned):

#Add legend
leg = ax1.legend(bbox_to_anchor=(0.03, 1.05), prop={'size':8})
leg.get_frame().set_alpha(0)
legText = pylab.gca().get_legend().get_texts()

#Format legend text
legText[0].set_color('#5998ff')
legText[1].set_color('#ffbb82')
legText[2].set_color('#d689c4')
for text in legText:
    text.set_ha('right')

推荐答案

据我所知,您无法删除破折号(我认为这是图例句柄),但可以将其替换为不可见的内容.例如,一个常见的问题是将图例句柄定义为彩色矩形.

As far as I know you can't remove the dashes (this is referred to as the legend handle I think) but you could replace it with something invisible. For example a common problem is to define the legend handle as a coloured rectangle.

基本思想是直接创建句柄,然后将要包括在图例中的所有项目作为两个列表传递.第一个列表是句柄,第二个列表是标签的文本.

The basic idea is to create the handle directly then pass all the items to be including in the legend as two lists. The first list being the handle and the second the text of the label.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle

x = np.linspace(0, 1)
p1, = plt.plot(x, np.cos(x))

leg1 = Rectangle((0, 0), 0, 0, alpha=0.0)
plt.legend([leg1], ['label'], handlelength=0)
plt.show()

我怀疑您需要对此进行一些操作才能获得您想要的确切外观.如果您不需要框架,则我建议使用这种方式调用plt.legend()时,请使用frameon=False参数,您无需担心相对于盒子的对齐方式.

I suspect you will need to play with this a bit to get the exact look your looking for. If you don't need the frame I might suggest using the frameon=False argument when calling plt.legend() this way you don't need to worry about the alignment with respect to the box.

这篇关于Matplotlib:删除行“破折号".并且仅在图例中显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆