Can i share the legends of multiple pandas plots in different axes?

Viewed 493

I would like to plot muiltiple stacked barplots in different axes, using Pandas and matplotlib

The problem with the following minimal example is that it creates a legend for each axis.

import pandas as pd
import matplotlib.pyplot as plt

d1 = {'a': 1, 'b': 10}
d2 = {'a': 5, 'b': 5}
df = pd.DataFrame([d1,d2])
d1 = {'a': 9, 'b': 3}
d2 = {'a': 5, 'b': 4}
df2 = pd.DataFrame([d1,d2])

fig, axes = plt.subplots(2,1,sharex=True)
df.plot.barh(stacked=True,ax=axes[0])
axes[0].set_ylabel('DataFrame 1')
df2.plot.barh(stacked=True,ax=axes[1])
axes[1].set_ylabel('DataFrame 2')

enter image description here

Is there a way to share the legend for all axes? Could the legend be moved outside the plotting area? The legens is probably quite large.

2 Answers

Turn off legend for second plot and set the position of first

fig, axes = plt.subplots(2,1,sharex=True)
df.plot.barh(stacked=True,ax=axes[0]).legend(bbox_to_anchor=(1.01, 1), loc='upper left')
axes[0].set_ylabel('DataFrame 1')
df2.plot.barh(stacked=True,ax=axes[1], legend=False)
axes[1].set_ylabel('DataFrame 2')

enter image description here

Yes, if all the legends are the same, you can grab one of them and place it on plt:

# grab the legend handles and lables
h, l = axes[0].get_legend_handles_labels()

# remove all the subplot legends
for ax in axes: ax.get_legend().remove()

# add one legend on `plt`
plt.legend(h,l, loc=(1.05, 0.8))

Output:

enter image description here

Related