Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save a figure in tiff with 600 dpi with compression using matplotlib?

Recently, I decided to port to Matplotlib from MATLAB for plotting my graphs. In MATLAB, what I would do is just go to files>export>render and then choose 600 dpi and then select apply to figure and then export. In Matplotlib, I am using the command savefig from the matplotlib library as

matplotlib.pyplot.savefig(fname, dpi=None, facecolor='w', edgecolor='w',
    orientation='portrait', papertype=None, format=None,
    transparent=False, bbox_inches=None, pad_inches=0.1,
    frameon=None).

Then I set dpi to 600 and .tiff as the output format. This works fine except that the file is very large ~32 mb. Well obviously, I can't use this much big of a file in a journal manuscript. I would like to know if there is a way to incorporate a compression to the file so that the image file can be obtained with a smaller size with no loss in the resolution.

like image 916
Shuf Avatar asked Mar 06 '18 10:03

Shuf


People also ask

How do I save matplotlib figures with high resolution?

To save the file in pdf format, use savefig() method where the image name is myImagePDF. pdf, format="pdf". We can set the dpi value to get a high-quality image. Using the saving() method, we can save the image with format=”png” and dpi=1200.

How do I save a figure as a TIFF in Python?

savefig(fname, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None). Then I set dpi to 600 and . tiff as the output format. This works fine except that the file is very large ~32 mb.

How do I save a high-quality figure in Python?

To get a high-quality image, we can use . eps image format. You can increase the dot per inch value, i.e., dpi. Using savefig() method, we can save the image locally.


1 Answers

Since matplotlib version 3.1.0 it is now possible to directly pass parameters to PIL when saving a figure via the kwarg pil_kwarg:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fig.savefig('/tmp/foo.tiff', dpi=600, format="tiff", pil_kwargs={"compression": "tiff_lzw"})

But beware of typos, since savefig seem to silently swallow unsupported kwargs, e.g. pil_kwargssss...

The feature was introduced in this PR which superseded the PR linked by Ignacio Vergara Kausel in his response.

like image 128
cchwala Avatar answered Sep 23 '22 00:09

cchwala