The standard way to get a legend in matplotlib, is to add a label=
parameter to the function involved. This also works for many seaborn functions. Seaborn even automatically creates the legend in that case. (For some functions the label needs to be inside a specific kw
dictionary.)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df2 = pd.DataFrame({'Month': ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'] * 2,
'Fans': np.random.randint(10, 100, 24),
'Type': ['Actual'] * 12 + ['Simulated'] * 12})
fig, ax = plt.subplots(figsize=(12, 8))
sns.barplot(ax=ax, x='Month', y='Fans', data=df2[df2['Type'] == 'Actual'], color='steelblue', label='Actual')
sns.lineplot(ax=ax, x='Month', y='Fans', data=df2[df2['Type'] == 'Simulated'], marker='o', sort=False,
color='darkorange', linewidth=6, dash_capstyle='round', label='Simulated')
ax.set_ylabel('kWh', size=15)
ax.set(xlabel=None)
ax.margins(x=0.02) # less white space at the left and the right
sns.despine()
plt.show()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…