Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can matplotlib add metadata to saved figures?

I want to be able to ascertain the provenance of the figures I create using matplotlib, i.e. to know which version of my code and data created these figures. (See this essay for more on provenance.)

I imagine the most straightforward approach would be to add the revision numbers of the code and data to the metadata of the saved figures, or as comments in a postscript file for example.

Is there any easy way to do this in Matplotlib? The savefig function doesn't seem to be capable of this but has someone come up with a workable solution?

like image 558
ihuston Avatar asked May 10 '12 11:05

ihuston


People also ask

Does Matplotlib overwrite Savefig?

Matplotlib Savefig will NOT overwrite old files.

How do I save a figure in Matplotlib?

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.

What does PLT Savefig do?

savefig() As the name suggests savefig() method is used to save the figure created after plotting data. The figure created can be saved to our local machines by using this method.

Which function can be used to save generated graph in Matplotlib to PNG?

Syntax of savefig() function fname : path or name of output file with extension. If extension is not provided plot is saved as png file.


2 Answers

I don't know of a way using matplotlib, but you can add metadata to png's with PIL:

f = "test.png" METADATA = {"version":"1.0", "OP":"ihuston"}  # Create a sample image import pylab as plt import numpy as np X = np.random.random((50,50)) plt.imshow(X) plt.savefig(f)  # Use PIL to save some image metadata from PIL import Image from PIL import PngImagePlugin  im = Image.open(f) meta = PngImagePlugin.PngInfo()  for x in METADATA:     meta.add_text(x, METADATA[x]) im.save(f, "png", pnginfo=meta)  im2 = Image.open(f) print im2.info 

This gives:

{'version': '1.0', 'OP': 'ihuston'} 
like image 77
Hooked Avatar answered Sep 19 '22 14:09

Hooked


If you are interested in PDF files, then you can have a look at the matplotlib module matplotlib.backends.backend_pdf. At this link there is a nice example of its usage, which could be "condensed" into the following:

import pylab as pl import numpy as np from matplotlib.backends.backend_pdf import PdfPages  pdffig = PdfPages('figure.pdf')  x=np.arange(10)  pl.plot(x) pl.savefig(pdffig, format="pdf")  metadata = pdffig.infodict() metadata['Title'] = 'Example' metadata['Author'] = 'Pluto' metadata['Subject'] = 'How to add metadata to a PDF file within matplotlib' metadata['Keywords'] = 'PdfPages example'  pdffig.close() 
like image 25
Alessandro Avatar answered Sep 17 '22 14:09

Alessandro