how to display metadata in scatter plot in matplotlib?

how to display metadata in scatter plot in matplotlib?

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()

Answer

Matplotlib does not offer a built-in function in its core library to enable hover effects. For this functionality, you may consider using the mplcursors 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

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles