0
0
Matplotlibdata~30 mins

Pick events for data interaction in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Pick Events for Data Interaction with Matplotlib
📖 Scenario: You are working with a simple scatter plot showing sales data points for different products. You want to make the plot interactive so that when you click on a point, it shows the product name and sales value.
🎯 Goal: Create a scatter plot with clickable points using Matplotlib's pick events. When a point is clicked, display the product name and sales value in the console.
📋 What You'll Learn
Create a dictionary called sales_data with product names as keys and sales numbers as values
Create a variable called fig, ax to set up the Matplotlib figure and axes
Plot the sales data as a scatter plot with picker=True to enable picking
Define a function called on_pick that prints the product name and sales value when a point is clicked
Connect the pick event to the on_pick function
Display the plot with plt.show()
💡 Why This Matters
🌍 Real World
Interactive plots help users explore data visually by clicking on points to get more details, useful in sales analysis, scientific data, and dashboards.
💼 Career
Data scientists and analysts often create interactive visualizations to communicate insights clearly and allow stakeholders to explore data dynamically.
Progress0 / 4 steps
1
Create the sales data dictionary
Create a dictionary called sales_data with these exact entries: 'Apples': 50, 'Bananas': 75, 'Cherries': 30, 'Dates': 90, 'Elderberries': 45.
Matplotlib
Need a hint?

Use curly braces {} to create a dictionary with the exact keys and values.

2
Set up the Matplotlib figure and axes
Import matplotlib.pyplot as plt. Create a figure and axes using fig, ax = plt.subplots().
Matplotlib
Need a hint?

Use import matplotlib.pyplot as plt and then plt.subplots() to create the figure and axes.

3
Plot the scatter plot with picker enabled
Plot the sales data as a scatter plot on ax using ax.scatter(). Use the product indices as x-values and sales values as y-values. Set picker=True to enable picking.
Matplotlib
Need a hint?

Convert the dictionary keys and values to lists. Use range(len(products)) for x-values and sales for y-values. Enable picking with picker=True.

4
Add pick event handler and show plot
Define a function called on_pick(event) that prints the product name and sales value of the clicked point. Connect this function to the figure's pick event using fig.canvas.mpl_connect('pick_event', on_pick). Finally, call plt.show() to display the plot.
Matplotlib
Need a hint?

Use event.ind[0] to get the index of the clicked point. Print the product and sales using that index. Connect the event with fig.canvas.mpl_connect.