Search code examples
python-3.xmatplotlibmatplotlib-table

Change or set font properties of matplotlib table


I have a table in matplotlib, which I would to change the font properties of, e.g. change the font family and font size. I can change the font size, as shown below based on the post here: How to change the table's fontsize with matplotlib.pyplot . However, I cannot find a way to change other front properties of the table, e.g. the font family. I looked through the properties of the returned Table, but cannot see any properties with relevance as suggested here Matplotlib table formatting.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows=1, ncols=1)
ax.axis("off")
my_table = ax.table(
     cellText=[[1., 1.25, 1.],
               [1.5, 1., 2.7],
               [3., 2.7, 1.]],
      rowLabels=['row1', 'row2', 'row3'],
      colLabels=['col1', 'col2', 'col3'],
      loc='center'
)

my_table.auto_set_font_size(False)
my_table.set_fontsize(12)

My question: How can I change fontproperties of a matplotlib table more specific the font family (preferably without going through rcParams['font.family'] = 'sans-serif')


Solution

  • I found a sketchy solution in which I alter the text._fontproperties of each cell as follows in continuation of the code above:

    my_table.auto_set_font_size(False)
    my_table.set_fontsize(12)
    
    for cell in my_table._cells:
        text = my_table._cells[cell].get_text()
        text.set_fontstyle('italic')
    
        # Or alternatively
        my_table._cells[cell]._text._fontproperties._family = 'serif'