Interactive Data Visualization with Python Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This lab will walk you through how to interact data with multiple canvases. By selecting and highlighting a point on one axis, you will generate the data of that point on the other axis. We will be using Python Matplotlib for this lab.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} matplotlib/figures_axes -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} matplotlib/line_plots -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} matplotlib/event_handling -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/booleans -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/conditional_statements -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/lists -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/tuples -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/dictionaries -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/function_definition -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/importing_modules -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/standard_libraries -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/classes_objects -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/constructor -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/polymorphism -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/encapsulation -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/math_random -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/numerical_computing -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/data_visualization -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} python/build_in_functions -.-> lab-48649{{"`Interactive Data Visualization with Python Matplotlib`"}} end

Import Libraries

We will start by importing the necessary libraries.

import numpy as np
import matplotlib.pyplot as plt

Generate Data

We will generate random data using NumPy.

np.random.seed(19680801)
X = np.random.rand(100, 200)
xs = np.mean(X, axis=1)
ys = np.std(X, axis=1)

Create Figure and Axes

We will create a figure with two axes.

fig, (ax, ax2) = plt.subplots(2, 1)

Plot Data

We will plot the generated data on the first axis.

line, = ax.plot(xs, ys, 'o', picker=True, pickradius=5)

Create Point Browser Class

We will create a class to handle the point browser functionality.

class PointBrowser:
    def __init__(self):
        self.lastind = 0

        self.text = ax.text(0.05, 0.95, 'selected: none',
                            transform=ax.transAxes, va='top')
        self.selected, = ax.plot([xs[0]], [ys[0]], 'o', ms=12, alpha=0.4,
                                 color='yellow', visible=False)

    def on_press(self, event):
        if self.lastind is None:
            return
        if event.key not in ('n', 'p'):
            return
        if event.key == 'n':
            inc = 1
        else:
            inc = -1

        self.lastind += inc
        self.lastind = np.clip(self.lastind, 0, len(xs) - 1)
        self.update()

    def on_pick(self, event):

        if event.artist != line:
            return True

        N = len(event.ind)
        if not N:
            return True

        ## the click locations
        x = event.mouseevent.xdata
        y = event.mouseevent.ydata

        distances = np.hypot(x - xs[event.ind], y - ys[event.ind])
        indmin = distances.argmin()
        dataind = event.ind[indmin]

        self.lastind = dataind
        self.update()

    def update(self):
        if self.lastind is None:
            return

        dataind = self.lastind

        ax2.clear()
        ax2.plot(X[dataind])

        ax2.text(0.05, 0.9, f'mu={xs[dataind]:1.3f}\nsigma={ys[dataind]:1.3f}',
                 transform=ax2.transAxes, va='top')
        ax2.set_ylim(-0.5, 1.5)
        self.selected.set_visible(True)
        self.selected.set_data(xs[dataind], ys[dataind])

        self.text.set_text('selected: %d' % dataind)
        fig.canvas.draw()

Connect Event Handlers

We will connect the event handlers to the figure canvas.

browser = PointBrowser()

fig.canvas.mpl_connect('pick_event', browser.on_pick)
fig.canvas.mpl_connect('key_press_event', browser.on_press)

Display Plot

We will display the plot.

plt.show()

Summary

In this lab, we learned how to interact data with multiple canvases using Python Matplotlib. We created a class to handle the point browser functionality and connected event handlers to the figure canvas to enable interactivity.

Other Python Tutorials you may like