pyplot legend label being truncated

左心房为你撑大大i 提交于 2019-12-11 00:13:21

问题


I'm trying to create a legend that will contain the color of the line it corresponds to and the label. My current code is plotting the legend but is only plotting the first letter of the label (D instead of DL11). I'm wondering how I can get my plot to stop truncating the label. I'd like to be able to add more lines and corresponding colors/labels in the future. Any help would be greatly appreciated. thanks

from numpy import *
import matplotlib.pyplot as plt
import pylab


data = loadtxt("/home/***")
d, tno1, qno1 = data[:,1], data[:,2], data[:,3]                         
d, tno1, qno1 = loadtxt("/home/***", usecols = (1,2,3), unpack=True)


plt.plot(tno1, qno1, label='DL11')
plt.legend( ('DL11') )
plt.show()

回答1:


You have hit an interesting un-packing issue.

Either

 plt.legend()

or

 plt.legend(('DL11',)) # <- note the comma

will get the desired result.

To understand why it does this, see the code at https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_axes.py#L422

calling plt.legend(('DL11')) in equivalent to calling plt.legend('DL11') which falls into the len(args) == 1 case, it then zips your string against the list of lines -> generates the label of 'D' as you only have one line.

Don't think this is a bug, but it is subtle.




回答2:


I believe pyplot expects a list of legends. For a one-item list, like yours, just

pyplot.legend(['DL11'])

My guess is that pyplot.legend('DL11') gets the list's first item, that is 'D'.

Hope it helps



来源:https://stackoverflow.com/questions/17978837/pyplot-legend-label-being-truncated

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