Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - save a figure with the same size and setting

I plot figures a lot during my python (through Spyder env.) usage. However, when I try to use plt.savefig('figure.png'), the saved figure has a different size from the inline figure plotted on Spyder.

For ex., when I use this command:

 plt.savefig('fig1.png')

The saved figure looks like this:

enter image description here

Note that there's something weird with the saved figure, e.g.: the title is cropped, the size is not proportional.

However, the following is the inline figure: enter image description here

I tried to modify the size through matplotlib.pyplot documentation but couldn't find such setting. Does anyone know how to save the figure with the exact setting as the inline plot?

like image 786
Muhammad Rayyan Avatar asked Nov 18 '25 21:11

Muhammad Rayyan


1 Answers

The inline figure size plotted in Spyder (or any other IDE or editor) depends on how the editor handles showing figures.

If you want to have an exact size as output of your code, use figsize before plotting code. (It uses inches)

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 10))

# Code to produce figure

You can also determine DPI when creating figure or saving.

plt.figure(figsize=(10, 10), dpi=300)

# or

plt.savefig(file_path, dpi=300)
like image 163
farshad Avatar answered Nov 21 '25 09:11

farshad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!