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 put text outside Python plots?
To put text outside a Python plot, you can control the text position by adjusting coordinates and using the transform parameter. The transform parameter determines the coordinate system used for positioning the text.
Steps
- Create data points for x and y
- Initialize the text position coordinates
- Plot the data using
plot()method - Use
text()method withtransform=plt.gcf().transFigureto position text outside the plot area - Display the figure using
show()method
Example
Here's how to place text outside the plot area using figure coordinates ?
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 5, 100)
y = np.exp(x)
# Text position in figure coordinates (0 to 1)
text_pos_x = 0.60
text_pos_y = 0.50
plt.plot(x, y, c='red')
plt.text(text_pos_x, text_pos_y, r"$\mathit{y}=e^{x}$", fontsize=14,
transform=plt.gcf().transFigure, color='green')
plt.show()
Understanding Transform Parameter
The transform parameter controls the coordinate system ?
-
plt.gcf().transFigure? Uses figure coordinates (0 to 1) -
plt.gca().transAxes? Uses axes coordinates (0 to 1) -
plt.gca().transData? Uses data coordinates (default)
Multiple Text Positions
You can place text at different positions outside the plot ?
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(8, 6))
plt.plot(x, y, 'b-', linewidth=2)
# Text outside plot area using figure coordinates
plt.text(0.1, 0.9, "Top Left", transform=plt.gcf().transFigure,
fontsize=12, color='red')
plt.text(0.9, 0.9, "Top Right", transform=plt.gcf().transFigure,
fontsize=12, color='blue')
plt.text(0.5, 0.02, "Bottom Center", transform=plt.gcf().transFigure,
fontsize=12, color='green')
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()
Conclusion
Use transform=plt.gcf().transFigure with coordinates between 0 and 1 to place text outside the plot area. The transform parameter controls whether coordinates are relative to the figure, axes, or data.
Advertisements
