Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use matplotlib tight layout with Figure?

I found tight_layout function for pyplot and want to use it. In my application I embed matplotlib plots into Qt GUI and use figure and not pyplot. Is there any way I can apply tight_layout there? Would it also work if I have several axes in one figure?

like image 608
Ekaterina Mishina Avatar asked Mar 07 '12 14:03

Ekaterina Mishina


People also ask

What is tight layout in Matplotlib?

Tight_layout Pad in Matplotlib The tight_layout method in Matplotlib dynamically recreates a subplot to accommodate within the plot area. import numpy as np. import matplotlib. pyplot as plt. fig, ax = plt.

How do you make subplots not overlap?

Often you may use subplots to display multiple plots alongside each other in Matplotlib. Unfortunately, these subplots tend to overlap each other by default. The easiest way to resolve this issue is by using the Matplotlib tight_layout() function.


1 Answers

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt  #-- In your case, you'd do something more like: # from matplotlib.figure import Figure # fig = Figure() #-- ...but we want to use it interactive for a quick example, so  #--    we'll do it this way fig, axes = plt.subplots(nrows=4, ncols=4)  for i, ax in enumerate(axes.flat, start=1):     ax.set_title('Test Axes {}'.format(i))     ax.set_xlabel('X axis')     ax.set_ylabel('Y axis')  plt.show() 

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt  fig, axes = plt.subplots(nrows=4, ncols=4)  for i, ax in enumerate(axes.flat, start=1):     ax.set_title('Test Axes {}'.format(i))     ax.set_xlabel('X axis')     ax.set_ylabel('Y axis')  fig.tight_layout()  plt.show() 

enter image description here

like image 102
Joe Kington Avatar answered Sep 22 '22 17:09

Joe Kington