Matplotlib: Remove line “dashes” and only display

2019-06-01 09:24发布

问题:

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

回答1:

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

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.