How to Set Aspect Ratio in Matplotlib: Simple Guide
To set the aspect ratio in
matplotlib, use the ax.set_aspect() method on your axes object. You can specify values like 'equal' for equal scaling or a numeric ratio like 1.5 to control width to height ratio.Syntax
The main way to set aspect ratio in Matplotlib is by calling set_aspect() on an axes object.
ax.set_aspect('equal'): Makes one unit in x equal to one unit in y, so circles look like circles.ax.set_aspect('auto'): Default, lets Matplotlib adjust aspect ratio automatically.ax.set_aspect(number): Sets the ratio of y-unit to x-unit. For example,1.5means y is 1.5 times x.
python
ax.set_aspect(aspect, adjustable='box')Example
This example shows how to create a plot with equal aspect ratio so shapes keep their proportions.
python
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([0, 1, 2], [0, 1, 4], marker='o') ax.set_aspect('equal') ax.set_title('Plot with Equal Aspect Ratio') plt.show()
Output
A plot window showing points connected by lines with equal scaling on x and y axes, so the shape is not stretched.
Common Pitfalls
One common mistake is setting aspect ratio without considering the adjustable parameter, which controls how the axes box or data limits change.
Another is expecting set_aspect('equal') to always fill the figure; sometimes the plot area looks small because the axes box size is fixed.
Also, setting a numeric aspect ratio without understanding it means the ratio of y-unit to x-unit can lead to unexpected stretching.
python
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([0, 1], [0, 2], marker='o') # Wrong: aspect ratio set but adjustable not considered ax.set_aspect(1) ax.set_title('Incorrect Aspect Ratio Usage') plt.show() # Correct way fig, ax = plt.subplots() ax.plot([0, 1], [0, 2], marker='o') ax.set_aspect(1, adjustable='datalim') ax.set_title('Correct Aspect Ratio with adjustable') plt.show()
Output
Two plot windows: first with stretched axes, second with correct aspect ratio adjusting data limits.
Quick Reference
| Parameter | Description | Example Values |
|---|---|---|
| aspect | Sets the aspect ratio of the axes | 'auto', 'equal', numeric value like 1.5 |
| adjustable | Controls what changes to keep aspect ratio | 'box' (default), 'datalim' |
| anchor | Position of the axes in the figure | 'C' (center), 'SW' (bottom-left), etc. |
Key Takeaways
Use ax.set_aspect('equal') to make x and y units equal in length.
Numeric values in set_aspect control the ratio of y-unit to x-unit.
Adjust the 'adjustable' parameter to control how the plot area changes.
Without proper adjustment, plots may look stretched or squished.
Always test your aspect ratio visually to ensure correct proportions.