How to set legend marker size and alpha?
Asked Answered
C

4

14

I have a seaborn scatter plot (lmplot) with over 10K points. In order to perceive all the data, it works better when the plot size is larger (making the markers relatively small) and the alpha on the markers is low. However, this makes the markers on the legend difficult to distinguish. How does one set the marker size and marker alpha in Seaborn?

I see that g._legend has a markersize attribute, but directly setting it doesn't do anything.

Example

import numpy as np
import pandas as pd
import seaborn as sns

n_group = 4000

pos = np.concatenate((np.random.randn(n_group,2) + np.array([-1,-1]),
                      np.random.randn(n_group,2) + np.array([0.2, 1.5]),
                      np.random.randn(n_group,2) + np.array([0.6, -1.8])))
df = pd.DataFrame({"x": pos[:,0], "y": pos[:, 1], 
                   "label": np.repeat(range(3), n_group)})

g = sns.lmplot("x", "y", df, hue = "label", fit_reg = False, 
               size = 8, scatter_kws = {"alpha": 0.1})
g._legend.set_title("Clusters")

Scatter plot of three dense clusters of points, with different colors for each cluster. The cluster colors are easily distinguished in the plot, but the markers in the legend are barely visible.

Culmiferous answered 8/2, 2018 at 20:54 Comment(0)
P
22

You can do this by setting the alpha values of the legend markers themselves. You can also use _sizes to set the marker sizes in the same for loop:

n_group = 4000

pos = np.concatenate((np.random.randn(n_group,2) + np.array([-1,-1]),
                      np.random.randn(n_group,2) + np.array([0.2, 1.5]),
                      np.random.randn(n_group,2) + np.array([0.6, -1.8])))
df = pd.DataFrame({"x": pos[:,0], "y": pos[:, 1], 
                   "label": np.repeat(range(3), n_group)})

g = sns.lmplot("x", "y", df, hue = "label", fit_reg = False, 
               size = 8, scatter_kws = {"alpha": 0.1})
g._legend.set_title("Clusters")

for lh in g._legend.legendHandles: 
    lh.set_alpha(1)
    lh._sizes = [50] 
    # You can also use lh.set_sizes([50])

enter image description here

Prolegomenon answered 8/2, 2018 at 20:59 Comment(2)
For anyone else struggling with this, I found that with seaborn v 0.11.1 using a scatterplot I needed to use g.legend_.legendHandles rather than g._legend.legendHandles in @DavidG's answerRincon
Same here. I tried g.legend().legendHandles, and it changed the alpha level, but it also reset my manually set legend names.Betrothal
B
4

You can use plt.legend to manipulate with the legend properties, markerscale=2 will increase the marker size 2 fold as the orginal ones.

plt.legend(loc=[1.01,1.01], prop={'size': 13}, markerscale=2)
Benignant answered 31/10, 2023 at 9:53 Comment(0)
Y
0

the above did not work for me in a seaborn lineplot. This did:

g = sns.lineplot(data=df, x='X', y='Y', hue='HUE', ci=False, style='STYLE',
             markers=True, ms=16, dashes=False)

#get legend and change stuff
handles, lables = g.get_legend_handles_labels()
for h in handles:
    h.set_markersize(10)

# replace legend using handles and labels from above
lgnd = plt.legend(handles, lables, bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0, title='TITLE')
Yonkers answered 3/2, 2022 at 14:0 Comment(0)
D
0

As an addition to @DavidG and @Tommy Neeld:

The next deprecation came along (using regplot from seaborn 0.12.2 and matplotlib 3.7.1):

MatplotlibDeprecationWarning: The legendHandles attribute was deprecated in Matplotlib 3.7 and will be removed two minor releases later. Use legend_handles instead.

so it should now be: g.legend_.legend_handles:

Depress answered 21/7, 2023 at 8:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.