Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib savefig image trim

The following sample code will produce a basic line plot with no axes and save it as an SVG file:

import matplotlib.pyplot as plt plt.axis('off') plt.plot([1,3,1,2,3]) plt.plot([3,1,1,2,1]) plt.savefig("out.svg", transparent = True) 

How do I set the resolution / dimensions of the image? There is padding on all sides of the image beyond the line graph. How do I remove the padding so that the lines appear on the edge of the image?

like image 216
oden Avatar asked Jun 28 '10 04:06

oden


People also ask

How do I use Savefig in matplotlib?

Saving a plot on your disk as an image file Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.

Does PLT Savefig overwrite?

Matplotlib Savefig will NOT overwrite old files.

How do I get rid of whitespace in matplotlib?

To remove whitespaces at the bottom of a Matplotlib graph, we can use tight layout or autoscale_on=False.

How do I save a matplotlib plot without white space?

To removing white space around a saved image with Python matplotlib, we call plt. savefig with the bbox_inches argument set to 'tight' . to call savefig to save the flots to myfile. png.


1 Answers

I am continually amazed at how many ways there are to do the same thing in matplotlib.
As such, I am sure that someone can make this code much more terse.
At any rate, this should clearly demonstrate how to go about solving your problem.

>>> import pylab >>> fig = pylab.figure()  >>> pylab.axis('off') (0.0, 1.0, 0.0, 1.0) >>> pylab.plot([1,3,1,2,3]) [<matplotlib.lines.Line2D object at 0x37d8cd0>] >>> pylab.plot([3,1,1,2,1]) [<matplotlib.lines.Line2D object at 0x37d8d10>]  >>> fig.get_size_inches()    # check default size (width, height) array([ 8.,  6.]) >>> fig.set_size_inches(4,3)  >>> fig.get_dpi()            # check default dpi (in inches) 80 >>> fig.set_dpi(40)  # using bbox_inches='tight' and pad_inches=0  # I managed to remove most of the padding;  # but a small amount still persists >>> fig.savefig('out.svg', transparent=True, bbox_inches='tight', pad_inches=0) 

Documentation for savefig().

like image 59
mechanical_meat Avatar answered Oct 04 '22 08:10

mechanical_meat