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
Showing points coordinate in a plot in Python Matplotlib
To show point coordinates in a plot in Python Matplotlib, we can use the annotate() method to add text labels at specific positions. This technique is useful for displaying exact coordinate values directly on the plot.
Steps
Set the figure size and adjust the padding between and around the subplots.
Initialize a variable N and create x and y data points using NumPy.
Plot the points using
plot()method.Zip the x and y data points; iterate them and place coordinate annotations.
Display the figure using show() method.
Example
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
N = 5
x = np.random.rand(N)
y = np.random.rand(N)
plt.plot(x, y, 'r*')
for xy in zip(x, y):
plt.annotate('(%.2f, %.2f)' % xy, xy=xy)
plt.show()
Output
It will produce the following output ?
Customizing Coordinate Display
You can customize the appearance and position of coordinate labels ?
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
x = [1, 2, 3, 4, 5]
y = [2, 5, 3, 8, 6]
plt.figure(figsize=(8, 6))
plt.plot(x, y, 'bo-', markersize=8)
# Add coordinate annotations with offset and styling
for i, (xi, yi) in enumerate(zip(x, y)):
plt.annotate(f'({xi}, {yi})',
xy=(xi, yi),
xytext=(5, 5),
textcoords='offset points',
bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7),
fontsize=10)
plt.title('Plot with Coordinate Labels')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.grid(True, alpha=0.3)
plt.show()
Conclusion
Use annotate() with the xy parameter to display coordinates at specific points. Customize the appearance using bbox and xytext parameters for better readability and positioning.
