Explain Codes LogoExplain Codes Logo

How do I set the figure title and axes labels font size?

python
matplotlib
font-size
customization
Anton ShumikhinbyAnton Shumikhin·Jan 21, 2025
TLDR

To alter text size in your matplotlib plot, utilize the fontsize attribute in title, xlabel, and ylabel:

import matplotlib.pyplot as plt # Sample data plt.plot([1, 2, 3], [4, 5, 6]) # Apply font sizes (because size does matter!) plt.title('Your Title', fontsize=20) plt.xlabel('X Axis', fontsize=14) plt.ylabel('Y Axis', fontsize=14) plt.show()

You can modify fontsize=20 for the title and fontsize=14 for axis labels as per your requirement.

Mastering Fine Typography

For enhanced customization of fonts on different elements, use the fontdict parameter like a typography maestro:

plt.title('Elegant Title', fontdict={'fontsize': 20, 'fontweight': 'bold'}) # Bold and beautiful! plt.xlabel('Measured Parameters', fontdict={'fontsize': 14, 'fontstyle': 'italic'}) # Elegance personified! plt.ylabel('Values', fontdict={'fontsize': 14, 'color': 'green'}) # Green for go!

Global and Local Settings: Protocol Decoded

To maintain a uniform look across various plots, matplotlib.rcParams can establish global defaults:

import matplotlib as mpl mpl.rcParams['axes.titlesize'] = 20 # For title size that speaks volumes mpl.rcParams['axes.labelsize'] = 14 # For axes labels that play a supporting role

Use local settings to enforce a certain style, and prevent unintended global mutations.

Dynamically Adjusting Font Size

Circumstances often dictate dynamic changes to font sizes:

  • While resizing plots, enlarged fonts preserve legibility.
  • Scaling fonts with dimensions of images is paramount when creating visualizations for publication or presentations.

After tweaking font sizes, plt.draw() fetches a refreshed display.

Journal of Readability: Guidelines

  • Legend labels should be noticeably smaller than axes labels.
  • Legends can match the size of axes labels or can be a bit smaller.
  • While annotations matter, they should not upstage the main characters – the axes labels and title.