Add Mouse-Over Interactivity (via mplcursors)
Description:
This code adds mouse-over interactivity to a plot, allowing users to hover over points and get information about the selected data point
Code Explanation:
-
First, we create a DataFrame with sample data for products, their sales, and revenue.
-
We then group the data by 'Product' using the
.groupby()
method. -
After grouping, we use
.agg()
to calculate the total sales and total revenue for each product. -
This gives us a summary table showing total values for products like A, B, and C.
-
Next, we use matplotlib to make a bar chart from the summary table.
-
The bar chart shows total revenue per product, making it easy to compare performance.
-
This method is useful when working with large datasets where we need to summarize and visualize key insights.
Program:
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.backend_bases import MouseEvent
# Sample data
data = {'Product': ['A', 'B', 'C', 'D', 'E'],
'Revenue': [1000, 1500, 2000, 2500, 3000],
'Units Sold': [100, 150, 200, 250, 300]}
df = pd.DataFrame(data)
# Create a figure and axis for plotting
fig, ax = plt.subplots()
# Scatter plot
scatter = ax.scatter(df['Revenue'], df['Units Sold'])
# Custom cursor tool for mouse-over interaction
class CursorTool:
def __init__(self, ax, scatter, df):
self.ax = ax
self.scatter = scatter
self.df = df
self.fig = ax.figure
self.cid = self.fig.canvas.mpl_connect('motion_notify_event', self.trigger)
def trigger(self, event):
# Get the mouse position
if event.inaxes != self.ax:
return
mouse_x, mouse_y = event.xdata, event.ydata
distances = ((self.scatter.get_offsets()[:, 0] - mouse_x) ** 2 +
(self.scatter.get_offsets()[:, 1] - mouse_y) ** 2) ** 0.5
closest_point = distances.argmin()
# Get the closest point data
product = self.df.iloc[closest_point]['Product']
revenue = self.df.iloc[closest_point]['Revenue']
units_sold = self.df.iloc[closest_point]['Units Sold']
# Print the details
print(f"Product: {product}, Revenue: {revenue}, Units Sold: {units_sold}")
# Initialize the cursor tool
cursor = CursorTool(ax, scatter, df)
# Show the plot
plt.show()
Output: