In matplotlib how to make part of a label smaller?
Sep 15, 3:37pm

In Matplotlib, you can make part of a label (e.g., a substring in a title, axis label, or annotation) smaller by using LaTeX formatting or mixed font sizes with matplotlib.text.Text. Here are two common approaches:


1. Using LaTeX Formatting

If your label contains LaTeX, you can wrap the part you want to resize in \small, \footnotesize, \tiny, etc.

Example:

python
import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1])
plt.title(r"Main Title \small{(smaller subtitle)}")
plt.show()
  • \small{...} makes the enclosed text smaller.
  • Other LaTeX size commands: \tiny, \scriptsize, \footnotesize, \small, \normalsize, \large, \Large, \huge, \Huge.

2. Using matplotlib.text.Text with Mixed Font Sizes

For non-LaTeX labels, you can manually create a Text object with mixed font sizes.

Example:

python
import matplotlib.pyplot as plt
from matplotlib.text import Text

fig, ax = plt.subplots()
ax.plot([0, 1], [0, 1])

# Create a combined label with different font sizes
label = "Main Title "
small_part = Text(0.5, 1.05, "(smaller subtitle)",
                  fontsize=8, ha='center', transform=ax.transAxes)
ax.set_title(label)
ax.add_artist(small_part)

plt.show()

3. Using plt.text for Annotations

If you're adding text as an annotation, you can use plt.text with different font sizes for parts of the text.

Example:

python
import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1])
plt.text(0.5, 0.5, "Main Text\n", fontsize=12, ha='center')
plt.text(0.5, 0.45, "Smaller Text", fontsize=8, ha='center')
plt.show()

4. Using span in Annotations (Advanced)

For more control, you can use matplotlib.offsetbox to create a custom annotation with mixed font sizes.

Example:

python
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText

fig, ax = plt.subplots()
ax.plot([0, 1], [0, 1])

# Create a custom annotation with mixed font sizes
text = "Main Title\n" + r"{\footnotesize smaller subtitle}"
at = AnchoredText(text, loc='upper center', frameon=False)
ax.add_artist(at)

plt.show()

Which Method to Use?

  • For simple cases: Use LaTeX (Method 1).
  • For non-LaTeX or dynamic labels: Use Text objects (Method 2 or 3).
  • For complex annotations: Use offsetbox (Method 4).
Sep 15, 3:37pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more