I can generate a matplotlib table (without any visibly associated plot) in a jupyter notebook, but when I try to save it to a PDF using matplotlib's internal backend_pdf.PdfPages
wrapper, it never appears centered on a page.
I've tried messing with 'top'
,'center'
,'bottom'
, and offsets and savefig(pad_inches)
to no avail. Here's my example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
col_names = ["this", "that","the other","4","5","6"]
page_data = np.random.randint(100, size=(40,6))
# stringify numbers: tables can't have ints in them.
for idx, sub in enumerate(page_data):
page_data[idx] = [str(i) for i in sub]
fig, axs = plt.subplots(1, figsize=(10,8))
axs.axis('off')
_table = plt.table(
cellText=page_data,
colLabels=col_names,
loc='top',
edges='open',
colLoc='right')
# and now, the PDF doesn't fit on page
pdf = PdfPages('test.pdf')
pdf.savefig(fig)
pdf.close()
My intuition is that there is still an invisible figure taking up space, and that's pushing up all the content on my page. How do I obliterate that figure, or size it to zero and only PDF the table text?
screenshot of Jupyter output (note the large blank space after table)
Using loc='center'
should solve this issue, and for the minimal example in question it does,
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
col_names = ["this", "that","the other","4","5","6"]
data = np.random.randint(100, size=(40,6)).astype('str')
fig, ax = plt.subplots(1, figsize=(10,10))
ax.axis('off')
_table = plt.table(cellText=data, colLabels=col_names,
loc='center', edges='open', colLoc='right')
pdf = PdfPages('test.pdf')
pdf.savefig(fig)
pdf.close()
It is important to note however, that this will position the table in the 'center' relative to the current Axes
instance. It is probably safer to use the matplotlib.axes.Axes.table
version if you are using multiple subplots since it allows finer control of which Axes
is used.
Note - I have tested this in Matplotlib 2.2.5 and 3.2.1, if the code above does produce the result I have shown, consider updating your Matplotlib installation.