Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PNG options to produce smaller file size when using savefig

I am using matplotlib to produce a plot which I then save to a PNG file using matplotlib.pyplot.savefig.

It all works fine, but the filesize is quite large (about 120Kb).

I can use ImageMagik afterwards (via the shell) to reduce the filesize to 38Kb without any loss of quality by reducing the number of colors and turning off dither:

convert +dither -colors 256 orig.png new.png

My question is: can I do this within matplotlib? I have searched the documentation and can't find any thing pertaining to setting the number of colors used when saving, etc....

Thanks!

like image 285
ccbunney Avatar asked May 28 '12 12:05

ccbunney


People also ask

How do you save a figure in PNG format with the name sine curve?

Answer: Use savefig() function to save the plot.

How do you export a plot into a PNG image file using Matplotlib?

To save plot figure as JPG or PNG file, call savefig() function on matplotlib. pyplot object. Pass the file name along with extension, as string argument, to savefig() function.

How do you change the size of a figure in Matplotlib?

Import matplotlib. To change the figure size, use figsize argument and set the width and the height of the plot. Next, we define the data coordinates. To plot a bar chart, use the bar() function. To display the chart, use the show() function.


3 Answers

This is what I do to run matplotlib image through PIL (now Pillow)

import cStringIO
import matplotlib.pyplot as plt
from PIL import Image

...

ram = cStringIO.StringIO()
plt.savefig(ram, format='png')
ram.seek(0)
im = Image.open(ram)
im2 = im.convert('RGB').convert('P', palette=Image.ADAPTIVE)
im2.save( filename , format='PNG')
like image 78
daryl Avatar answered Oct 20 '22 17:10

daryl


You can pass a dpi= kwarg to savefig() which might help you reduce the filesize (depending on what you want to do with your graphs afterwards). Failing that, I think that the Python Imaging Library ( http://www.pythonware.com/products/pil/ ) will almost certainly do what you want.

like image 27
FakeDIY Avatar answered Oct 20 '22 16:10

FakeDIY


I don't know about doing this within matplotlib, but you could always do it using PythonMagick once you've written the file to disk.

like image 43
dwurf Avatar answered Oct 20 '22 18:10

dwurf