Is there any way to use the line plotted in a figure in matplotlib as the handle in the legend? I'm thinking for example in this basic code rather than a straight line in the legend have a small version of the sine wave I've plotted as the handle.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,15,0.1)
y = [np.sin(x1) for x1 in x]
plt.plot(x,y, label = 'sine wave')
plt.legend()
plt.show()
Thanks in advance!
The answer by @DizietAsahi gives the correct result for the simple example, but would fail for other x values. One may hence more generally use a transformed bbox such that one needs not care about the actual values of the data.
I thought this was a pretty fun question. Most of the information you need to solve your problem is provided in matplotlib's "Legend Guide". However, I definitely think the documentation is a little sparse.
The key to solving your question is to create a new "handler" that will be called when trying to draw the legend of your artist, and that returns an artists, which can have any properties or shape. In this case, we simply create a new Line2D object with the correct data to draw a sine wave.