0406 Customizing Legends
中文版:自定义图例
Customizing Plot Legends
Plot legends give meaning to a visualization, assigning meaning to the various plot elements. We previously sawhowto create a simple legend; here we’lltakealookat customizing the placement and aesthetics of the legend in Matplotlib.
The simplest legend can be created with the plt.legend() command, which automatically creates a legend for any labeled plot elements:
import matplotlib.pyplot as plt
plt.style.use('classic')%matplotlib inline
import numpy as npx = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label='Sine')
ax.plot(x, np.cos(x), '--r', label='Cosine')
ax.axis('equal')
leg = ax.legend();But there aremanywayswemight want to customize such a legend. For example, we can specify the location andturnofftheframe:
ax.legend(loc='upper left', frameon=False)
figWecanusethe ncol command to specify the number of columns in the legend:
ax.legend(frameon=False, loc='lower center', ncol=2)
figWecanusea rounded box (fancybox) oradda shadow, change the transparency (alpha value) oftheframe, or change the padding around the text:
ax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)
figFor more information on available legend options, see the plt.legend docstring.