Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib adjust figure margin

The following code gives me a plot with significant margins above and below the figure. I don't know how to eliminate the noticeable margins. subplots_adjust does not work as expected.

import matplotlib.pyplot as plt import numpy as np  fig = plt.figure() ax = fig.add_subplot(111) ax.plot(range(10),range(10)) ax.set_aspect('equal') plt.tight_layout() 

tight_layout eliminates some of the margin, but not all of the margins.

What I wanted is actually setting the aspect ratio to any customized value and eliminating the white space at the same time.

Update: as Pierre H. puts it, the key is to change the size of the figure container. So my question is: Could you suggest a way to accommodate the size of the figure to the size of the axes with arbitrary aspect ratio?

In other words, first I create a figure and an axes on it, and then I change the size of the axes (by changing aspect ratio for example), which in general will leave a portion of the figure container empty. At this stage, we need to change the size of the figure accordingly to eliminate the blank space on the figure container.

like image 527
wdg Avatar asked Sep 04 '13 17:09

wdg


People also ask

How do I change the margins in Matplotlib?

Plot t and y data points using plot() method. Set the title of the plot. Set margins of the plot using margins(x=0, y=0). To display the figure, use show() method.

How do I increase white space in Matplotlib?

We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.


2 Answers

I just discovered how to eliminate all margins from my figures. I didn't use tight_layout(), instead I used:

import matplotlib.pyplot as plt fig = plt.figure(figsize=(20,20)) ax = plt.subplot(111,aspect = 'equal') plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) 

Hope this helps.

like image 169
Minh Avatar answered Sep 24 '22 05:09

Minh


After plotting your chart you can easily manipulate margins this way:

plot_margin = 0.25  x0, x1, y0, y1 = plt.axis() plt.axis((x0 - plot_margin,           x1 + plot_margin,           y0 - plot_margin,           y1 + plot_margin)) 

This example could be changed to the aspect ratio you want or change the margins as you really want. In other stacktoverflow posts many questions related to margins could make use of this simpler approach.

Best regards.

like image 44
Nuno Aniceto Avatar answered Sep 24 '22 05:09

Nuno Aniceto