get point values from a scatter plot in matplotlib
Assistant
To get the point values from a scatter plot in matplotlib, you can access the data that was used to create the scatter plot. Here are a few ways to do this:
Method 1: Store the data in variables
When you create the scatter plot, store the x and y data in separate variables. Then, you can access these variables later to get the point values.
import matplotlib.pyplot as plt
Create some data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
Create the scatter plot
plt.scatter(x, y)
Get the point values
point_values = list(zip(x, y))
print(point_values) # Output: [(1, 2), (2, 4), (3, 6), (4, 8), (5, 10)]
Copied Method 2: Access the plot's data
If you have already created the scatter plot and didn't store the data in variables, you can access the plot's data using the get_offsets() method of the PathCollection object returned by plt.scatter().
import matplotlib.pyplot as plt
Create some data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
Create the scatter plot
scatter = plt.scatter(x, y)
Get the point values
point_values = scatter.get_offsets()
print(point_values) # Output: [[1. 2.], [2. 4.], [3. 6.], [4. 8.], [5. 10.]]
Copied Note that get_offsets() returns a numpy array of shape (n, 2), where n is the number of points in the scatter plot.
Method 3: Use the pick_event
If you want to get the point values interactively, you can use the pick_event functionality of matplotlib. This allows you to click on a point in the scatter plot and retrieve its coordinates.
import matplotlib.pyplot as plt
Create some data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
Create the scatter plot
scatter = plt.scatter(x, y, picker=5) # Set the pick radius to 5 points
def onpick(event):
if event.inaxes is not None:
point_index = event.ind[0]
x_value = x[point_index]
y_value = y[point_index]
print(f"Clicked on point ({x_value}, {y_value})")
plt.show()
Copied In this example, when you click on a point in the scatter plot, the onpick function is called, which prints the coordinates of the clicked point.