Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use multiple font sizes in one label in Python Matplotlib?
To use multiple font sizes in one label in Python Matplotlib, you can combine different text elements or use LaTeX formatting with size commands. This allows creating visually appealing labels with varying emphasis.
Method 1: Using LaTeX Size Commands
The most effective way is using LaTeX size commands like \large, \small, and \huge within a single title ?
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [8, 4]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 100)
y = np.cos(x)
plt.plot(x, y, 'b-', linewidth=2)
# Multiple font sizes in one title using LaTeX
plt.title(r"$\huge{Function:}$ $\large{y = \cos(x)}$ $\small{(continuous)}$",
fontsize=14)
plt.grid(True, alpha=0.3)
plt.show()
Method 2: Using Text Annotations
Place multiple text elements at different positions with varying font sizes ?
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
x = np.linspace(-2, 2, 100)
y = x**2
ax.plot(x, y, 'r-', linewidth=2)
# Multiple text elements with different sizes
ax.text(0.5, 0.95, 'Quadratic', transform=ax.transAxes,
fontsize=20, weight='bold', ha='center')
ax.text(0.5, 0.85, 'Function', transform=ax.transAxes,
fontsize=16, ha='center')
ax.text(0.5, 0.75, 'y = x²', transform=ax.transAxes,
fontsize=12, ha='center', style='italic')
plt.grid(True, alpha=0.3)
plt.show()
Method 3: Combining Text with Different Properties
Use formatted strings with matplotlib's text rendering for mixed sizing ?
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
ax.plot(x, y, 'g-', linewidth=2)
# Using fontdict for different parts
title_text = "Sine Wave Analysis"
subtitle_text = "Amplitude: 1, Period: 2?"
ax.text(0.5, 0.95, title_text, transform=ax.transAxes,
fontsize=18, weight='bold', ha='center')
ax.text(0.5, 0.88, subtitle_text, transform=ax.transAxes,
fontsize=12, ha='center', color='gray')
plt.grid(True, alpha=0.3)
plt.show()
Comparison of Methods
| Method | Complexity | Best For |
|---|---|---|
| LaTeX Commands | Low | Mathematical expressions |
| Text Annotations | Medium | Precise positioning |
| Multiple Text Elements | High | Complex layouts |
LaTeX Size Commands
Common LaTeX size commands you can use:
\tiny- Smallest size\small- Small text\large- Large text\Large- Larger text\huge- Huge text
Conclusion
Use LaTeX size commands for simple mixed-size titles in mathematical contexts. For complex layouts with precise control, combine multiple text elements with different font properties and positions.
