How to get different font sizes in the same annotation of Matplotlib?

To add different font sizes in the same annotation method, we can create multiple annotations with varying font sizes at different positions. This technique is useful for creating visually appealing text displays with hierarchical information.

Step-by-Step Approach

  • Make lists of x and y data points where text could be placed.
  • Initialize a variable 'labels', i.e., a string.
  • Make a list of sizes of the fonts.
  • Use subplots() method to create a figure and a set of subplots.
  • Iterate above lists and annotate each label's text and set its fontsize.
  • To display the figure, use show() method.

Example

Here's how to create annotations with different font sizes ?

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

X = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8]
Y = [0.1, 0.12, 0.13, 0.20, 0.23, 0.25, 0.27]
labels = 'Welcome'
sizes = [10, 20, 30, 40, 50, 60, 70]

fig, ax = plt.subplots()

for x, y, label, size in zip(X, Y, labels, sizes):
    ax.annotate(f"$\it{label}$", (x, y), fontsize=size, color='red')

plt.show()

Advanced Example with Different Text Content

You can also use different text content for each annotation ?

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 6))

# Different positions, text content, and font sizes
positions = [(0.1, 0.8), (0.3, 0.6), (0.5, 0.4), (0.7, 0.2)]
texts = ['Title', 'Subtitle', 'Content', 'Footer']
font_sizes = [24, 18, 14, 10]
colors = ['black', 'blue', 'green', 'gray']

for (x, y), text, size, color in zip(positions, texts, font_sizes, colors):
    ax.annotate(text, (x, y), fontsize=size, color=color, 
                fontweight='bold' if size > 20 else 'normal')

ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title('Multiple Font Sizes in Annotations')
plt.show()

Key Parameters

  • fontsize − Controls the size of the text
  • color − Sets the text color
  • fontweight − Controls text boldness ('normal', 'bold', 'light')
  • fontstyle − Sets text style ('normal', 'italic', 'oblique')

Conclusion

Using different font sizes in matplotlib annotations allows you to create hierarchical text displays. Combine this with varying colors and positions to create visually appealing and informative plots.

Updated on: 2026-03-25T21:29:12+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements