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
Place text inside a circle in Matplotlib
To place text inside a circle in Matplotlib, we can create a Circle patch and use the text() method to position text at the circle's center coordinates.
Steps to Place Text Inside a Circle
Create a new figure using
figure()methodAdd a subplot to the current axis
Create a Circle instance using
Circle()classAdd the circle patch to the plot
Use
text()method to place text at circle coordinatesSet axis limits and display the figure
Example
Here's how to create a circle with centered text ?
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Set figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create figure and subplot
fig = plt.figure()
ax = fig.add_subplot(111)
# Create a circle at center (0, 0) with radius 1
circle = patches.Circle((0, 0), radius=1, color='yellow', alpha=0.7)
ax.add_patch(circle)
# Place text at the center of the circle
plt.text(0, 0, "Circle Text", ha='center', va='center', fontsize=12, fontweight='bold')
# Set axis limits and make axes equal
plt.xlim([-2, 2])
plt.ylim([-2, 2])
plt.axis('equal')
plt.title("Text Inside Circle")
plt.show()
Multiple Circles with Text
You can create multiple circles with different text positions ?
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots(figsize=(8, 6))
# Circle data: (x, y, radius, color, text)
circles_data = [
(2, 3, 0.8, 'lightblue', 'Blue'),
(5, 3, 1.0, 'lightcoral', 'Red'),
(3.5, 1, 0.6, 'lightgreen', 'Green')
]
# Create circles and add text
for x, y, radius, color, text in circles_data:
circle = patches.Circle((x, y), radius, color=color, alpha=0.7)
ax.add_patch(circle)
ax.text(x, y, text, ha='center', va='center', fontsize=10, fontweight='bold')
# Set limits and equal aspect ratio
ax.set_xlim(0, 7)
ax.set_ylim(0, 5)
ax.set_aspect('equal')
ax.set_title('Multiple Circles with Text')
plt.grid(True, alpha=0.3)
plt.show()
Key Parameters
| Parameter | Purpose | Common Values |
|---|---|---|
ha |
Horizontal alignment | 'center', 'left', 'right' |
va |
Vertical alignment | 'center', 'top', 'bottom' |
fontsize |
Text size | 8, 10, 12, 14, etc. |
alpha |
Circle transparency | 0.0 (transparent) to 1.0 (opaque) |
Conclusion
Use patches.Circle() to create circles and text() with ha='center', va='center' to center text perfectly inside circles. Set axis('equal') to maintain circular shape.
Advertisements
