Customize legend marker facecolor in scatterplot with patches

Viewed 1098

I have a scatter plot that also contains an ellipse. However, the legend only contains the formatting from the Ellipse. How can I also reflect the formatting from the scatter plot?

In the example below, I'd like the legend markers to be filled just like in the scatter plot.

x = np.random.randn(60) 
y = np.random.randn(60)

fig,ax=plt.subplots()
sb.scatterplot(x, y,color='red', ax=ax)
ellipse = matplotlib.patches.Ellipse( 
                xy=(0, 0), width=2, height=3, angle=45, 
                edgecolor='red', facecolor='none'
            )
ax.add_patch(ellipse)

ax.legend(['A'])
plt.show()

enter image description here

1 Answers

Matplotlib's standard way is to assign a label to each item to appear in the legend. Only in case the standard way wouldn't give the desired result, the legend can be customized.

Calling ax.legend() without parameters creates the default legend. Customized handles can be created with Patch' and Line2D` as in the code below.

import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import numpy as np
import seaborn as sns

x = np.random.randn(60)
y = np.random.randn(60)

fig, ax = plt.subplots()
sns.scatterplot(x, y, color='red', ax=ax, label='scatter dots')
ellipse = Ellipse(xy=(0, 0), width=2, height=3, angle=45,
                  edgecolor='red', facecolor='none', label='ellipse')
ax.add_patch(ellipse)

handles, labels = ax.get_legend_handles_labels()
new_handles = [Patch(facecolor='white', edgecolor='red', hatch='ooo'),
               Line2D([0], [0], marker='o', markerfacecolor='red', markeredgecolor='black', markersize=10, ls='')]
ax.legend(new_handles, labels)
plt.show()

example plot

Related