Unique legend in Seaborn and Matplotlib subplots

  Kiến thức lập trình

I am analysing some data and plotting three violin plots on two subplots using matplotlib and seaborn.

My problem is with the legends, I would like to have just one legend for the subplot outside them.

A MWE is:

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

df = pd.DataFrame({"A": np.random.uniform(size=100), "B": np.random.uniform(size=100), "Class": np.random.randint(0, 4, 100)})

fig, axs = plt.subplots(1, 2, sharey=True)

sns.violinplot(ax=axs[0], data=df[["A", "Class"]], x="Class", y="A")
axs[0].legend(["A"])

sns.violinplot(ax=axs[1], data=df[["B", "Class"]], x="Class", y="B", color="r")
axs[1].legend(["B"])

plt.show()

violin plot example

This example put one legend for each subplot, I want both of them together in the right side of the plot.

If I tried to extract the header and label in this way lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes], but this is a list of empty tuple.

I tried to add a label option to the plots and plot the legend plt.legend(loc="center left", bbox_to_anchor=(1.0, 0.5)), but I obtain the same result of the plot I attached with the same legend repeated 4 times.

Any suggestion?

LEAVE A COMMENT