1plt.plot([1, 2, 3], label='Inline label')
2plt.legend(loc=1, prop={'size': 16})
3
4
1import numpy as np
2import matplotlib.pyplot as plt
3
4x = np.linspace(0, 20, 1000)
5y1 = np.sin(x)
6y2 = np.cos(x)
7
8plt.plot(x, y1, "-b", label="sine")
9plt.plot(x, y2, "-r", label="cosine")
10plt.legend(loc="upper left")
11plt.ylim(-1.5, 2.0)
12plt.show()
1# Short answer:
2# matplotlib.pyplot places the legend in the "best" location by default
3# To add a legend to your plot, call plt.legend()
4
5# Example usage:
6import matplotlib.pyplot as plt
7x1 = [1, 2, 3] # Invent x and y data to be plotted
8y1 = [4, 5, 6]
9x2 = [1, 3, 5]
10y2 = [6, 5, 4]
11
12plt.plot(x1, y1, label="Dataset_1") # Use label="data_name" so that the
13 # legend is easy to interpret
14plt.plot(x2, y2, label="Dataset_2")
15plt.legend(loc='best')
16plt.show()
17
18# Other legend locations you can specify:
19Location String Location Code (e.g. loc=1)
20'best' 0
21'upper right' 1
22'upper left' 2
23'lower left' 3
24'lower right' 4
25'right' 5
26'center left' 6
27'center right' 7
28'lower center' 8
29'upper center' 9
30'center' 10
1import numpy as np
2import matplotlib.pyplot as plt
3
4def example_legend():
5 plt.clf()
6 x = np.linspace(0, 1, 101)
7 y1 = np.sin(x * np.pi / 2)
8 y2 = np.cos(x * np.pi / 2)
9 plt.plot(x, y1, label='sin')
10 plt.plot(x, y2, label='cos')
11 plt.legend()
12