Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib.pyplot.imshow: removing white space within plots when using attributes "sharex" and "sharey"

I have a problem which is similar to the one posted here. The difference is that I get unwanted white spaces inside the plot area when I plot two subplots which share axes via the sharex and sharey attributes. The white spaces persist even after setting autoscale(False). For example, using similar code as in the answer to the post mentioned above:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
ax.imshow(np.random.random((10,10)))
ax.autoscale(False)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax, sharey=ax)   # adding sharex and sharey
ax2.imshow(np.random.random((10,10)))
ax2.autoscale(False)
plt.show()

results in this image.

I have also tried ax.set_xlim(0, 10) and ax.set_xbound(0, 10) as per suggestions here, but to no avail. How can I get rid of the extra white spaces? Any ideas would be appreciated.

like image 891
mlynn Avatar asked Feb 25 '13 22:02

mlynn


People also ask

Does Imshow normalize image?

By default, imshow normalizes the data to its min and max. You can control this with either the vmin and vmax arguments or with the norm argument (if you want a non-linear scaling).

What is CMAP in PLT Imshow?

Per the help(plt.imshow) docstring: cmap : ~matplotlib.colors.Colormap , optional, default: None. If None, default to rc image.cmap value. cmap is ignored when X has RGB(A) information. However, if img were an array of shape (M,N) , then the cmap controls the colormap used to display the values.

How do I remove the margins in matplotlib?

The python plotting library matplotlib will by default add margins to any plot that it generates. They can be reduced to a certain degree through some options of savefig() , namely bbox_inches='tight' and pad_inches=0 .

What is Sharex and sharey in python?

Controls sharing of properties among x ( sharex ) or y ( sharey ) axes: True or 'all': x- or y-axis will be shared among all subplots. False or 'none': each subplot x- or y-axis will be independent. 'row': each subplot row will share an x- or y-axis. 'col': each subplot column will share an x- or y-axis.


1 Answers

As suggested here, adding:

ax.set_adjustable('box-forced')
ax2.set_adjustable('box-forced')

solves the problem.

(documentation)

like image 195
mlynn Avatar answered Oct 17 '22 08:10

mlynn