Keyreall
Keyreall

Reputation: 97

Create an artificial legend in seaborn

I want to add an artificial legend to my plot. It is artificial because I didn't group my observation (see code below).It means I can't solve this problem with plt.legend() function: it requires grouped variables. Is there any way to handle it? My code:

sns.set(rc={'figure.figsize':(11.7,8.27)})
sns.set_theme(style="white")
ax = sns.boxplot(data = data.values.tolist(),palette=['white', 'black'])
ax.set_xticklabels(labels, fontsize=14)
ax.tick_params(labelsize=14) 

and plot looks like: enter image description here

My desire is to add a legend (maybe it is not a legend at all just a drawing) where will be written something like (sorry for size):enter image description here

Upvotes: 0

Views: 488

Answers (2)

JohanC
JohanC

Reputation: 80289

You can create a legend from the artists created by Seaborn as follows:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

sns.set_theme(style="white")
ax = sns.boxplot(data = np.random.randn(20,20), palette=['white', 'black'])

handles = ax.artists[:2]
handles[0].set_label("First")
handles[1].set_label("Second")
ax.legend(handles=handles)
plt.show()

seaborn boxplot with custom legend

Upvotes: 1

GabrielP
GabrielP

Reputation: 782

As I do not have your data, I can not replicate your charts. However, you might try adding the following line at the end (after importing matplotlib.pyplot as plt).

plt.legend(['First','Second'])

Upvotes: 1

Related Questions