1

I have a scatter plot. I want to add some metadata to each point in my scatter plot. looking at documentation , i found annotate function( matplotlib.pyplot.annotate) , has anyone use this or some other function , such that we can add metadata to each point or are there are similar libraries, like matplotlib, which can display metadata , on clicking/hovering individual points in the scatterplot?

import matplotlib.pyplot as plt
import numpy as np

# Generate random data for x and y axes
x = np.random.rand(20)
y = np.random.rand(20)
colors = np.random.rand(20)
area = (30 * np.random.rand(20))**2  # point radii

# Create the scatter plot
plt.scatter(x, y, s=area, c=colors, alpha=0.5)

# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')

# Display the plot
plt.show()

1 Answer 1

2

Matplotlib does not offer a built-in function in its core library to enable hover effects. For this functionality, you may consider using the mplcursor library. Kindly try running the code below after installing mplcursors.

import matplotlib.pyplot as plt
import numpy as np
import mplcursors

x = np.random.rand(20)
y = np.random.rand(20)
colors = np.random.rand(20)
area = (30 * np.random.rand(20))**2

metadata = [f"Point {i}, Value: ({x[i]:.2f}, {y[i]:.2f})" for i in range(len(x))]

fig, ax = plt.subplots()
scatter = ax.scatter(x, y, s=area, c=colors, alpha=0.5)

plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Interactive Scatter Plot')

cursor = mplcursors.cursor(scatter, hover=True)

@cursor.connect("add")
def on_add(sel):
    sel.annotation.set_text(metadata[sel.index])

plt.show()

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.