Search code examples
pythonmatplotlibsvg

how to add comment to SVG file written by matplotlib?


Given an example plot

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,4,6])
plt.savefig('simple.plot.svg')

how can I write a comment into that SVG file?

for example, I would like to write that the SVG file was written by simple.plot.py

I have seen there may be a way to add comments: https://matplotlib.org/stable/api/backend_svg_api.html I am not a python or matplotlib expert, however, and I don't know how I could implement that.

I was hoping that something like plt.savefig('simple.plot.svg', comment = "written by simple.plot.py") would be available, but alas, this functionality doesn't seem to exist: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html#matplotlib.pyplot.savefig

but I have no idea how I could implement that into a simple script like I have above, how can I do so?


Solution

  • plt.savefig accepts an argument metadata which should be a dictionary with keys being strings and values dependent on the desired output format.

    For SVG, the keys and values should follow the Dublin Core standard.

    Here, the key should be 'Creator' and the value the name of the program as string:

    plt.savefig('simple.plot.svg', metadata={'Creator': 'simple.plot.py'})