Hacker News new | ask | show | jobs
by rkp8000 1216 days ago
Just in case anyone hasn't tried it before, the "tight_layout" keyword in matplotlib is a game changer. Instantiating a figure via e.g. "fig, axs = plt.subplots(1, 2, figsize=(6, 3), tight_layout=True)" automatically arranges the labels and subplot boundaries etc to not bump into each other. It doesn't work 100% of the time, but it usually does a pretty good job and has honestly saved me a ton of plotting headaches.
3 comments

In my experience, `tight_layout` tends to work best after all objects have been drawn:

  fig, axs = plt.subplots(ncols=2, figsize=(6, 3))
  fig.suptitle('Two Made-Up Plots')
  axs[0].plot(np.sinc(np.linspace(-5, 5)))
  axs[1].imshow(np.random.normal(size=(10, 10)))
  fig.tight_layout()  # works really well here!
More here: https://matplotlib.org/stable/tutorials/intermediate/tight_l...

You can also use `constrained_layout`, but in my experience it often doesn't work as well (e.g., the plots end up looking too cluttered for my taste), and also, `constrained_layout` can be noticeably slower (e.g., if you're drawing a large number of complex plots): https://matplotlib.org/stable/tutorials/intermediate/constra...

Please don't recommended right layout anymore. There is a new, much better layouting engine since a few release you can get with `layout="constrained"`
If tight_layout doesnt do the job, adding a ‘bbox_inches = tight’ may do it. I dont know why though.