Search code examples
pythonmatplotlibgraphseaborn

Make seaborn line graph same width as legend


I would like to stretch the following graph out horizontally so as to fill up all the space; instead of white space to the right of the graph, I would like the x-axis to be stretched out so the line graph is as broad as the legend. It does not have to be exact or automatic; I would be happy with a solution where I manually adjust the width.

Graph as produced by current code:

Current code:

import matplotlib.pyplot as plt
import seaborn as sns

sns.lineplot(data=df_wide)
plt.legend(ncol=4, loc='upper left', bbox_to_anchor=(0.0, -.1), )
plt.xticks(rotation=90, ha='right', rotation_mode='anchor')
plt.xlabel("")
plt.ylabel("Pct. of bios")

I have tried adding:

plt.gca().set_aspect(80)

but whatever the number I choose, that only stretches and shrinks the graph vertically, without changing its width proportional to the legend. (on a sidenote, I have no idea why I need to make this number so huge; setting it to 1 causes the whole line graph area to be completely flattened into a horizontal line).

Graph when trying to add .set_aspect()

I have also tried adding:

plt.figure(figsize=(18, 6))

at the end, or:

sns.set(rc={'figure.figsize':(18, 6)})

before creating the figure, but no matter the numbers, that does not change anything about the width ratio between plot and legend either. (note that the second suggestion is the accepted answer to a related question but it does not work here)

I would prefer not to solve this by changing the legend font size, because then I would have to manually adjust the other label fonts sizes as well (so they don't look huge compared to the legend).


Solution

  • Would you consider using a relplot that takes height and aspect arguments also?

    ax = sns.relplot(data=flights_wide, kind="line", height = 8, aspect = 1.25)
    

    enter image description here