0

This code creates following PNG file though, This wasn't what I want.

import seaborn as sns
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2,figsize=(20, 6),gridspec_kw={'height_ratios': [2,1]})
                       
fmri = sns.load_dataset("fmri")
flights = sns.load_dataset("flights")

sns.lineplot(data=fmri, x="timepoint", y="signal", hue="event", ax=ax[0])
ax[0].legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.)
        
sns.lineplot(data=flights, x="year", y="passengers", ax=ax[1])
fig.savefig("test.png")

enter image description here

How can I make the width of second plot longer like this?
It looks easy, but I'm stuck on it..

enter image description here

Edit

The method I came up with was to use GridSpec like a following code, but it is complicated and not intuitive. There is another method that uses ax[0].get_position(), like Redox san taught me, but it is not good enough. I just want to increase the width of second plot a bit, however, Increasing the width of second plot doesn't work. I am still looking for another way.

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(20, 10))
gs = GridSpec(2, 2, width_ratios=[100,1], height_ratios=[2,1])

ax = []
ax.append(plt.subplot(gs.new_subplotspec((0, 0))))
plt.subplot(gs[0,1]).axis('off')
ax.append(plt.subplot(gs.new_subplotspec((1, 0), colspan=2)))

fmri = sns.load_dataset("fmri")
flights = sns.load_dataset("flights")

sns.lineplot(data=fmri, x="timepoint", y="signal", hue="event", ax=ax[0])
ax[0].legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.)
        
sns.lineplot(data=flights, x="year", y="passengers", ax=ax[1])
fig.savefig("test.png")
masaya
  • 410
  • 2
  • 9
  • 15

1 Answers1

1

you can do this by adjusting the widths of the subplots. After plotting (just before save), add these lines. This will get the width information and you can adjust the ratio to what you want it to be

gPos = ax[0].get_position()
gPos.x1 = 0.83  # I have used 83% to set the first plot to be of 83% of original width
ax[0].set_position(gPos)

The plot

enter image description here

Redox
  • 9,321
  • 5
  • 9
  • 26
  • This is easy and efficient way! Thanks. By the way, increasing the size of the second plot did not work. `gPos = ax[1].get_position() gPos.x1 = 1.2 ax[1].set_position(gPos) ` – masaya Jul 05 '22 at 09:45
  • 1
    Yes, it will increase the size if you use 1.1 or 1.3. But, the increase is not even/linear and sometimes unpredictable. So, I use the reduction, which is usually more consistent – Redox Jul 05 '22 at 10:28