pythonmatplotlibpdf-generationsectionspdfpages

How to make a 1-cell table headers with Matplotlib?


I am using Matplotlib's PdfPages to plot various figures and tables from queried data and generate a Pdf. I want to group plots by various sections such as "Stage 1", "Stage 2", and "Stage 3", by essentially creating section headers. For example, in a Jupyter notebook I can make cell's markdown and create bolded headers. However, I am not sure how to do something similar with PdfPages. One idea I had was to generate a 1 cell table containing the section title. Instead of creating a 1 cell table, it has a cell per character in the title.

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12, 2))
ax = plt.subplot(111)
ax.axis('off')
tab = ax.table(cellText=['Stage 1'], bbox=[0, 0, 1, 1])
tab.auto_set_font_size(False)
tab.set_fontsize(24)

This results in the following output: enter image description here

If anyone has suggestions for how to create section headers or at least fix the cell issue in the table I created, I would appreciate your input. Thanks!


Solution

  • You need to use colLabels to name the columns and use the cellText with a corresponding shape

    import matplotlib.pyplot as plt
    fig = plt.figure(figsize=(12, 2))
    ax = plt.subplot(111)
    ax.axis('off')
    
    length = 7
    colLabels = ['Stage %s' %i for i in range(1,length+1)] # <--- 1 row, 7 columns
    cellText = np.random.randint(0, 10, (1,length))
    
    tab = ax.table(cellText=cellText, colLabels=colLabels, bbox=[0, 0, 1, 1], cellLoc = 'center')
    tab.auto_set_font_size(False)
    tab.set_fontsize(14)
    

    enter image description here

    Table with multiple rows

    cellText = np.random.randint(0, 10, (3,length)) # <--- 3 rows, 7 columns
    
    tab = ax.table(cellText=cellText, colLabels=colLabels, bbox=[0, 0, 1, 1], cellLoc = 'center')
    

    enter image description here

    To get a single row with multiple columns starting from 2 rows, 7 columns

    tab = ax.table(cellText=[['']*length], colLabels=colLabels, bbox=[0, 0, 1, 1], cellLoc = 'center')
    cells=tab.get_celld()
    
    for i in range(length):
        cells[(1,i)].set_height(0)
    

    enter image description here

    Getting a single column Using in the above code

    length = 1
    

    produces

    enter image description here