Matplotlib: Remove line “dashes” and only display text in legend

空扰寡人 提交于 2019-12-23 01:46:05

问题


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.



来源:https://stackoverflow.com/questions/23434844/matplotlib-remove-line-dashes-and-only-display-text-in-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!