I need to include a line into a figure every time a button is clicked (I'm using pyqt4), this line has to be labeled and I also need to compare these lines with a constant function. Here is what I've tried:
labels = []
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='white')
ax.hold(True)
def function(k):
x = np.linspace(0, 2, 100)
y = np.sin(k * np.pi * x) * np.exp(-5 * x)
labels.append('k = {}'.format(k))
ax.plot(x, y)
# reference line
plt.axhline(y=0.1, c='k', linestyle='--')
plt.legend(labels)
for i in range(0,5):
function(i)
plt.show()
The result: 
There is a simple way to skip the constant line marker in the legend frame?
Best How To :
Maybe I'm not following but it doesn't look like your reference line axhline(y=0.1, ...)
is included in the legend.
I would set this separately, no reason to redraw it every time you plot a new line. Also try passing the label
inside the plot
function
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='white')
ax.hold(True)
# reference line - only draw this once
plt.axhline(y=0.1, c='k', linestyle='--')
def function(k):
x = np.linspace(0, 2, 100)
y = np.sin(k * np.pi * x) * np.exp(-5 * x)
ax.plot(x, y, linestyle='-', label='k = {}'.format(k)) # set label attribute for line
for i in range(0,5):
function(i)
plt.legend() # you only need to call this once, it will generate based on the label assigned to line objects
plt.show()
Note: If you want to do this interactively (i.e. draw on a button press) then you'll have to call plt.legend()
upfront and call plt.draw()
after each new line is added, that way it'll update the legend.