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 get the center of a set of points using Python?
To get the center of a set of points, we calculate the centroid by finding the average of all x-coordinates and y-coordinates. This gives us the geometric center of the point cloud.
Method: Calculate Arithmetic Mean
The center (centroid) is calculated as ?
Center X = sum(all x coordinates) / number of points
Center Y = sum(all y coordinates) / number of points
Example
Let's create a scatter plot and mark the center point ?
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Data points
x = [5, 1, 3, 2, 8]
y = [3, 6, 1, 0, 5]
# Plot the data points
plt.plot(x, y, 'bo-', label='Data Points')
# Calculate center (centroid)
center = (sum(x)/len(x), sum(y)/len(y))
print(f"Center coordinates: ({center[0]:.1f}, {center[1]:.1f})")
# Plot center point
plt.plot(center[0], center[1], marker='o', color='red', markersize=8, label='Center')
# Annotate the center
plt.annotate(
"center",
xy=center, xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
plt.legend()
plt.grid(True, alpha=0.3)
plt.title('Center of Point Set')
plt.show()
Center coordinates: (3.8, 3.0)
Using NumPy for Multiple Point Sets
For larger datasets or multiple point sets, NumPy provides efficient calculation ?
import numpy as np
# Multiple point sets
points = np.array([[5, 3], [1, 6], [3, 1], [2, 0], [8, 5]])
# Calculate center using NumPy
center = np.mean(points, axis=0)
print(f"Center using NumPy: ({center[0]:.1f}, {center[1]:.1f})")
# Alternative: separate x and y
x_coords = points[:, 0]
y_coords = points[:, 1]
center_alt = (np.mean(x_coords), np.mean(y_coords))
print(f"Alternative method: ({center_alt[0]:.1f}, {center_alt[1]:.1f})")
Center using NumPy: (3.8, 3.0) Alternative method: (3.8, 3.0)
Comparison of Methods
| Method | Best For | Performance |
|---|---|---|
Pure Python (sum()/len()) |
Small datasets, simple cases | Slower for large data |
NumPy (np.mean()) |
Large datasets, multiple dimensions | Fast, vectorized |
Conclusion
The center of points is calculated as the arithmetic mean of coordinates. Use sum()/len() for simple cases or np.mean() for efficient computation with larger datasets.
Advertisements
