Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase size of saved figure while keeping aspect ratio

I'm plotting data and saving it to a file.

import matplotlib.pyplot as plt
fig=plt.figure(figsize=(10,10))
plt.gca().set_aspect(1)
plt.scatter(range(10), range(0,20,2))
fig.savefig("test.jpg")

Is there an easy way to make the figure size larger, but without having to guess height/width values to keep aspect ratio as the axis?

It would be even harder if I had multiple subplots and I want to keep their fixed axis ratios. I want to control the figure size (scale), but not introduce empty borders in the figure.

like image 406
Gerenuk Avatar asked Mar 17 '23 05:03

Gerenuk


1 Answers

One way is to set new figure size with .set_size_inches:

zoom = 2
w, h = fig.get_size_inches()
fig.set_size_inches(w * zoom, h * zoom)

This should change the size while keeping proportions.

Another way is to increase dpi if you need different size for saved figure only:

fig, ax = plt.subplots(figsize=(10,10))
ax.set_aspect(1)
ax.scatter(range(10), range(0,20,2))
dpi = fig.get_dpi()   # This will get dpi that is set matplotlibrc
fig.savefig("test.jpg", dpi=dpi*2)  # Multiply dpi by whatever ration you want to increase the figure
like image 172
Primer Avatar answered Mar 19 '23 06:03

Primer