Skip to content

Instantly share code, notes, and snippets.

@SamWolski
Created August 17, 2021 09:46
Show Gist options
  • Save SamWolski/6a53bf12a84cde17bc37b103ca095b30 to your computer and use it in GitHub Desktop.
Save SamWolski/6a53bf12a84cde17bc37b103ca095b30 to your computer and use it in GitHub Desktop.
Add custom metadata to matplotlib pdfs
"""
Write metadata to pdf files with no warnings.
Useful for provenance, and in this way we can suppress warnings for end users of a larger application
"""
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import numpy as np
import warnings
##############################################################################
## Generate some data that we want to plot
x_data = np.linspace(0.0, 4.0, 101)
y_data = np.sin(x_data)
##############################################################################
## Save with metadata in savefig call
## This generates warnings! But still works
fig, axes = plt.subplots(1,1)
axes.plot(x_data, y_data, marker='o', linestyle='', color='C0')
fig.savefig("mpl_mdata_savefig.pdf", metadata={"Author": "Sam", "foo": "bar", "baz": "3"})
##############################################################################
## Let's write a function that let's us do this without the warnings!
def save_custom_pdf_metadata(fig_obj, target_path, metadata):
## Enter the context manager for the pdf object
with PdfPages(target_path) as pdf_obj:
## Get metadata InfoDict object
infodict = pdf_obj.infodict()
## Suppress warnings, but ONLY for the metadata addition step
with warnings.catch_warnings():
## Iterate over metadata elements and add them to infodict
for key, value in metadata.items():
infodict[key] = value
## Save the current figure
pdf_obj.savefig(fig_obj)
## Watch out for:
## - more possible kwargs in the call to savefig
## and/or
## - needs to be filtered by format at a higher level, as this only works for pdf!
##
return fig_obj
## Now using the custom function
fig, axes = plt.subplots(1,1)
axes.plot(x_data, y_data, marker='o', linestyle='', color='C0')
save_custom_pdf_metadata(fig, "mpl_mdata_suppressed.pdf", metadata={"Author": "Sam", "foo": "bar", "quux": "3"})
## In a real application, the metadata will be generated automatically
## All the user needs to do is say "here's the fig object, save this (as a pdf)".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment