Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

matplotlib - Add legend in overlapped Seaborn graph

enter image description here

I want to add legend for the bar char and line as Monitored and Simulated data. Could anyone help me ? And how to make the line as dash-line ?

fig,ax =plt.subplots(figsize=(12,8))
sns.barplot(ax=ax,x='Month',y='Fans',data= df2[df2['Type']=='Actual'], color = 'steelblue')
sns.lineplot(ax = ax,x= 'Month',y='Fans',data = df2[df2['Type']=='Simulated'], marker='o', sort = False,
             color= 'darkorange',linewidth=6,dash_capstyle='round')
ax.set_ylabel('kWh',size=15)
ax.set(xlabel=None)
sns.despine()
question from:https://stackoverflow.com/questions/65875539/add-legend-in-overlapped-seaborn-graph

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

example plot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...