matplotlib.pyplot, preserve aspect ratio of the plot

PythonMatplotlib

Python Problem Overview


Assuming we have a polygon coordinates as polygon = [(x1, y1), (x2, y2), ...], the following code displays the polygon:

import matplotlib.pyplot as plt
plt.fill(*zip(*polygon))
plt.show()

By default it is trying to adjust the aspect ratio so that the polygon (or whatever other diagram) fits inside the window, and automatically changing it so that it fits even after resizing. Which is great in many cases, except when you are trying to estimate visually if the image is distorted. How to fix the aspect ratio to be strictly 1:1?

(Not sure if "aspect ratio" is the right term here, so in case it is not - I need both X and Y axes to have 1:1 scale, so that (0, 1) on both X and Y takes an exact same amount of screen space. And I need to keep it 1:1 no matter how I resize the window.)

Python Solutions


Solution 1 - Python

Does it help to use:

plt.axis('equal')

Solution 2 - Python

'scaled' using plt

The best thing is to use:

 plt.axis('scaled')

As Saullo Castro said. Because with equal you can't change one axis limit without changing the other so if you want to fit all non-squared figures you will have a lot of white space.

Equal

enter image description here

Scaled

enter image description here

'equal' using ax

Alternatively, you can use the axes class.

fig = plt.figure()
ax = figure.add_subplot(111)
ax.imshow(image)
ax.axes.set_aspect('equal')

Solution 3 - Python

There is, I'm sure, a way to set this directly as part of your plot command, but I don't remember the trick. To do it after the fact you can use the current axis and set it's aspect ratio with "set_aspect('equal')". In your example:

import matplotlib.pyplot as plt
plt.fill(*zip(*polygon))
plt.axes().set_aspect('equal', 'datalim')
plt.show()

I use this all the time and it's from the examples on the matplotlib website.

Solution 4 - Python

Better plt.axis('scaling'), it works better if you want to modify the axes with xlim() and ylim().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHeadcrabView Question on Stackoverflow
Solution 1 - PythonOlivier VerdierView Answer on Stackoverflow
Solution 2 - PythonG MView Answer on Stackoverflow
Solution 3 - Pythonuser348863View Answer on Stackoverflow
Solution 4 - PythonledmikeView Answer on Stackoverflow