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()
1ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
2 ncol=3, fancybox=True, shadow=True)
1
2import matplotlib.pyplot as plt
3
4#define x and ysin
5plt.plot(x,ysin,label='sin(x)')
6plt.legend()
7plt.show()
8
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