0

I am trying to adjust the legend markers in a Seaborn jointplot. Based on the answer by "MaozGelbart" on this Github issue, I expected rcParams to work for this. The configurations are in the matplotib documentation here, and I think legend.markerscale is the parameter I am interested in.

How can I change the legend marker scale? This code below does not work. However, it does work for the legend.fontsize parameter.

import pandas as pd
import seaborn as sns

d = {
    'x': [3,2,5,1,1,0],
    'y': [1,1,2,3,0,2],
    'cat': ['a','a','a','b','b','b']
    }

df = pd.DataFrame(d)
with sns.plotting_context(rc={"legend.fontsize": 'x-small', "legend.markerscale": 0.5}):
    g = sns.jointplot(data=df, x='x', y='y', hue='cat')

enter image description here

There is a similar Stack Overflow question here but it looks like there is no clear answer. Besides, setting rcParams should work, in theory

a11
  • 3,122
  • 4
  • 27
  • 66

1 Answers1

1

According to Setting a fixed size for points in legend, calling .set_sizes([...]) on the legend handles should work.

For a jointplot() this would be called as:

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

d = {'x': [3, 2, 5, 1, 1, 0],
     'y': [1, 1, 2, 3, 0, 2],
     'cat': ['a', 'a', 'a', 'b', 'b', 'b']}

df = pd.DataFrame(d)
with sns.plotting_context(rc={"legend.fontsize": 'x-large'}):
    g = sns.jointplot(data=df, x='x', y='y', hue='cat')
for h in g.ax_joint.get_legend().legendHandles:
    h.set_sizes([10])
plt.show()

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • thanks, this works. any idea why `rcParams` does not work? is it a bug? – a11 Feb 26 '21 at 20:14
  • is there a Pythonic way to do `for h in g...` as a one-liner? Doing `test = [h for h in g.ax_joint.get_legend().legendHandles]` gets the handles into a list, but I am not sure how to apply the `set_sizes` – a11 Feb 26 '21 at 20:14
  • 1
    `[h.set_sizes(..) for h in g.ax_joint.get_legend().legendHandles]` would work, but I don't think that is the recommended Pythonic way. The `"legend.markerscale"` probably is meant for markers created with a line plot, not a scatter plot. Or maybe it is just some functionality that has changed. – JohanC Feb 26 '21 at 20:30