Customize Legend Marker Facecolor In Scatterplot With Patches
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?
Solution 1:
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()
Post a Comment for "Customize Legend Marker Facecolor In Scatterplot With Patches"