dimka
dimka

Reputation: 4579

saving figure with resizing in matplotlib

While displaying my plot in matplotlib, I'm also trying to save it as a png using different dimensions. I'm making a copy of my main figure (print_fig = fig), and then changing the print_fig size (print_fig.set_size_inches(7,3)). However this applies changes my original fig instead of just print_fig. Is there any way I can 'clone' a figure object?

My code looks something like this:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)
ax.set_ylabel("y-label")

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend()
#change dimension of figure for print 
#clone fig displayed
print_fig = fig
print_fig.set_size_inches(7,3)
print_fig.savefig('print_fig.png')
plt.show()

this is what my screen looks like: enter image description here

Upvotes: 4

Views: 6188

Answers (2)

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94485

Here is an idea: some Matplotlib backends do not display anything, if I remember correctly (like the pdf backend), so maybe you could switch to another backend, change the figure size (which will not be displayed on screen), and save it (and then switch back to the original backend).

I have not tested this idea, though, and the backend switching is still experimental. But it might be worth a try.

Upvotes: 0

tiago
tiago

Reputation: 23492

If what you want is to save a png in different resolutions, you don't need to resize the figure. You can just control the image size with the dpi keyword in savefig.

When you call savefig, by default it uses the rc savefig.dpi (you can check it on your .matplotlibrc file, it is typically 100). So if you want to change the resolution of the output file, you just scale the dpi by the amount you want:

plt.savefig('myfig100.png', dpi=100)
plt.savefig('myfig50.png', dpi=50)

The second one will have half the width and height of the first.

If you want to change the proportions of width/height, then of course this is of no help. What you are doing is the proper way to change the proportions of the figure for saving. But it will change your window, as you see. If you are not plotting anything else after the show(), you can do the following:

  1. Do your plotting calls
  2. Call show()
  3. Do fig.set_size_inches(7,3)
  4. Finally do your savefig()

This way, and unless you do further changes to your figure, you'll be able to save with the dimensions required and the figure on the screen will not update to those dimensions.

Upvotes: 1

Related Questions