How to change a table's fontsize with matplotlib.pyplot?

To change a table's fontsize with matplotlib, we can use the set_fontsize() method. This is useful when you want to make table text larger or smaller for better readability or to fit your visualization requirements.

Steps

  • Create a figure and a set of subplots
  • Generate sample data for the table
  • Create column labels
  • Turn off axis display for a clean table appearance
  • Create the table using table() method
  • Disable automatic font sizing with auto_set_font_size(False)
  • Set custom font size using set_fontsize() method
  • Display the figure using show() method

Example

Here's how to create a table with custom font size ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create subplot
fig, axs = plt.subplots(1, 1)

# Generate random data
data = np.random.random((5, 3))
columns = ("Column I", "Column II", "Column III")

# Turn off axis
axs.axis('tight')
axs.axis('off')

# Create table
the_table = axs.table(cellText=data, colLabels=columns, loc='center')

# Set custom font size
the_table.auto_set_font_size(False)
the_table.set_fontsize(12)

plt.show()

Comparing Different Font Sizes

Let's compare tables with different font sizes ?

import numpy as np
import matplotlib.pyplot as plt

# Create sample data
data = np.array([
    [0.25, 0.78, 0.43],
    [0.67, 0.12, 0.89],
    [0.34, 0.56, 0.21]
])
columns = ("Small", "Medium", "Large")

# Create subplots for comparison
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 4))

# Table with font size 8
ax1.axis('tight')
ax1.axis('off')
table1 = ax1.table(cellText=data, colLabels=columns, loc='center')
table1.auto_set_font_size(False)
table1.set_fontsize(8)
ax1.set_title('Font Size: 8')

# Table with font size 12
ax2.axis('tight')
ax2.axis('off')
table2 = ax2.table(cellText=data, colLabels=columns, loc='center')
table2.auto_set_font_size(False)
table2.set_fontsize(12)
ax2.set_title('Font Size: 12')

# Table with font size 16
ax3.axis('tight')
ax3.axis('off')
table3 = ax3.table(cellText=data, colLabels=columns, loc='center')
table3.auto_set_font_size(False)
table3.set_fontsize(16)
ax3.set_title('Font Size: 16')

plt.tight_layout()
plt.show()

Key Parameters

Method Purpose Example
auto_set_font_size(False) Disable automatic sizing Required before custom sizing
set_fontsize(size) Set custom font size 8, 12, 16, etc.
axis('off') Hide axis for clean table Common for table displays

Conclusion

Use auto_set_font_size(False) followed by set_fontsize() to control table text size in matplotlib. This gives you precise control over table readability and appearance in your visualizations.

Updated on: 2026-03-25T20:04:34+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements