Matplotlib: Remove line “dashes” and only display

2019-06-01 09:09发布

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

enter image description here

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

1条回答
【Aperson】
2楼-- · 2019-06-01 09:25

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

enter image description here

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.

查看更多
登录 后发表回答