问题
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