Home > Back-end >  How can I use .on(fig) without distorting the legend position in seaborn.objects?
How can I use .on(fig) without distorting the legend position in seaborn.objects?

Time:01-14

I am creating a plot in seaborn.objects. This plot has a legend, and I would also like to change its size.

This can be done using the .theme() method, which affects the matplotlib rcParams:

import matplotlib.pyplot as plt
import seaborn.objects as so
import pandas as pd

dat = pd.DataFrame({'group':['a','a','b','b'],
                    'x': [1, 2, 1, 2],
                    'y': [4, 3, 2, 1]})

# Choosing a very distorted figure size here so you can see when it works
(so.Plot(dat, x = 'x', y = 'y', color = 'group')
 .add(so.Line())
 .theme({'figure.figsize': (8,2)}))

Line graph with legend and (8,2) figure size

However, in order to solve the problem outlined in Line graph with legend and a figure size that is not (8,2)

I can, however, now set figsize in the plt.figure() function. But when I do this, the legend positioning is thrown much further out of whack and is largely cut off.

fig = plt.figure(figsize = (8,2))

# Choosing a very distorted figure size here so you can see when it works
(so.Plot(dat, x = 'x', y = 'y', color = 'group')
 .on(fig)
 .add(so.Line()))

Line graph with misplaced legend and (8,2) figure size

How can I include both .on(fig) with a legend without pushing the legend away? As pointed out in this enter image description here

  • Related