34

I'm drawing a table with matplotlib.axes.Axes.table like this:

    sub_axes.table(cellText=table_vals,
          colWidths = [0.15, 0.25],
          rowLabels=row_labels,
          loc='right')

I'd like to change the fontsize of table's content, and found there is a fontsize property.

So it becomes:

    sub_axes.table(cellText=table_vals,
          colWidths = [0.15, 0.25],
          rowLabels=row_labels,
          fontsize=12,
          loc='right')

But when I execute the code, I got an error:

TypeError: table() got an unexpected keyword argument 'fontsize'

Is this property deprecated? And how can I change the fontsize of table with pyplot?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Evans Y.
  • 4,209
  • 6
  • 35
  • 43

2 Answers2

57

I think the documentation is either hinting at a parameter-to-be (notice fontsize is not a link like the other parameters) or perhaps is a bit misleading at the moment. There is no fontsize parameter.

Digging through the source code, I found the Table.set_fontsize method:

table = sub_axes.table(cellText=table_vals,
                       colWidths = [0.15, 0.25],
                       rowLabels=row_labels,
                       loc='right')
table.set_fontsize(14)
table.scale(1.5, 1.5)  # may help

Here is an example with a grossly exaggerated fontsize just to show the effect.

import matplotlib.pyplot as plt
# Based on http://stackoverflow.com/a/8531491/190597 (Andrey Sobolev)

fig = plt.figure()
ax = fig.add_subplot(111)
y = [1, 2, 3, 4, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1]    
col_labels = ['col1', 'col2', 'col3']
row_labels = ['row1', 'row2', 'row3']
table_vals = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]

the_table = plt.table(cellText=table_vals,
                      colWidths=[0.1] * 3,
                      rowLabels=row_labels,
                      colLabels=col_labels,
                      loc='center right')
the_table.auto_set_font_size(False)
the_table.set_fontsize(24)
the_table.scale(2, 2)

plt.plot(y)
plt.show()

enter image description here

Amitku
  • 4,664
  • 2
  • 16
  • 17
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 23
    For this to work, I had to add `the_table.auto_set_font_size(False)` before set new font size – just-boris Jun 11 '13 at 23:08
  • the_table.set_fontsize was not working in my code, but a recreation did work. This comment and suggestion table.auto_set_font_size(False) fixed it. The question is, why did it need to be done in one script but not another? It was not set to true anywhere, and true does not appear to be the default. To try to troubleshoot I found in matplotlib.table the method get_fontsize(). But it doesn't work -- says Table object has no attribute 'get_fontsize'. – Blaine Kelley Nov 11 '22 at 16:17
42

Set the auto_set_font_size to False, then set_fontsize(24)

the_table.auto_set_font_size(False)
the_table.set_fontsize(24)
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42
Yunmeng Zhu
  • 421
  • 4
  • 2