By default Matplotlib resamples images created with imshow to
fit inside the parent Axes. This can mean that images that have very
different original sizes can end up appearing similar in size.
This example shows how to keep the images the same relative size, or
how to make the images keep exactly the same pixels as the original data.
Preserving relative sizes
By default the two images are made a similar size, despite one being 1.5 times the width
of the other:
Note that both images have an aspect ratio of 1 (i.e. pixels are square), but
pixels sizes differ because the images are scaled to the same width.
If the size of the images are amenable, we can preserve the relative sizes of two
images by using either the width_ratio or height_ratio of the subplots. Which
one you use depends on the shape of the image and the size of the figure.
We can control the relative sizes using the width_ratios argument if the images
are wider than they are tall and shown side by side, as is the case here.
While we are making changes, let us also make the aspect ratio of the figure closer
to the aspect ratio of the axes using figsize so that the figure does not have so
much white space. Note that you could alternatively trim extra blank space when
saving a figure by passing bbox_inches="tight" to savefig.
Given that the data subsample is in the upper left of the larger image,
it might make sense if the top of the smaller Axes aligned with the top of the larger.
This can be done manually by using set_anchor, and using "NW" (for
northwest).
The above approach with adjusting figsize and width_ratios does
not generalize well, because it needs manual parameter tuning, and
possibly even code changes to using height_ratios instead of
width_ratios depending on the aspects and layout of the images.
We can alternative calculate positions explicitly and place Axes at absolute
coordinates using add_axes. This takes the position in the form
[leftbottomwidthheight] and is in
figure coordinates. In the following, we
determine figure size and Axes positions so that one image data point
is rendered exactly to one figure pixel.
dpi=100# 100 pixels is one inch# All variables from here are in pixels:buffer=0.35*dpi# pixels# Get the position of A axesleft=bufferbottom=buffer
Inspection of the image will show that it is exactly 3* 35 + 300 + 200 = 605
pixels wide, and 2 * 35 + 100 = 170 pixels high (or twice that if the 2x
version is used by the browser instead). The images should be rendered with
exactly 1 pixel per data point (or four, if 2x).