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
Selected Reading
How to add a variable to Python plt.title?
To add a variable to Python plt.title(), you can use string formatting methods like f-strings, format(), or the % operator. This allows you to dynamically include variable values in your plot titles.
Basic Example with Variable in Title
Here's how to include a variable in your matplotlib title ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure properties
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create data points
x = np.linspace(-1, 1, 10)
num = 2
y = num ** x
# Plot with variable in title
plt.plot(x, y, c='red')
plt.title(f"y = {num}^x")
plt.show()
Different String Formatting Methods
Using f-strings (Recommended)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
slope = 2.5
intercept = 1.2
y = slope * x + intercept
plt.plot(x, y)
plt.title(f"Linear Function: y = {slope}x + {intercept}")
plt.show()
Using format() Method
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
amplitude = 3
frequency = 2
y = amplitude * np.sin(frequency * x)
plt.plot(x, y)
plt.title("Sine Wave: y = {}sin({}x)".format(amplitude, frequency))
plt.show()
Using % Operator
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
coefficient = 0.5
y = coefficient * x**2
plt.plot(x, y)
plt.title("Quadratic Function: y = %.1fx²" % coefficient)
plt.show()
Multiple Variables in Title
You can include multiple variables in your title ?
import matplotlib.pyplot as plt
import numpy as np
# Parameters
n_points = 50
mean = 5
std_dev = 2
# Generate data
data = np.random.normal(mean, std_dev, n_points)
plt.hist(data, bins=10, alpha=0.7)
plt.title(f"Normal Distribution (n={n_points}, ?={mean}, ?={std_dev})")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
Comparison of Methods
| Method | Syntax | Best For |
|---|---|---|
| f-strings | f"Title {variable}" |
Most readable, Python 3.6+ |
| format() | "Title {}".format(var) |
Complex formatting, older Python |
| % operator | "Title %d" % var |
Simple numeric formatting |
Conclusion
Use f-strings for the most readable code when adding variables to plot titles. The format() method works well for complex formatting, while the % operator is useful for simple numeric displays.
Advertisements
