Pylab with Gtk3 Sgskip

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to use the Matplotlib library to create and modify figure windows. We will also explore how to customize the GUI by accessing the underlying GTK widgets.

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/PlotCustomizationGroup(["`Plot Customization`"]) 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/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/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} matplotlib/importing_matplotlib -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} matplotlib/figures_axes -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} matplotlib/line_plots -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} matplotlib/legend_config -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} matplotlib/event_handling -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/booleans -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/conditional_statements -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/for_loops -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/lists -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/tuples -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/sets -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/function_definition -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/lambda_functions -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/importing_modules -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/using_packages -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/data_visualization -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} python/build_in_functions -.-> lab-48885{{"`Pylab with Gtk3 Sgskip`"}} end

Import Libraries

First, we need to import the necessary libraries. We will be using Matplotlib, GTK3, and the Gtk module from the gi.repository.

import matplotlib
matplotlib.use('GTK3Agg')  ## or 'GTK3Cairo'
import gi
import matplotlib.pyplot as plt
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

Create Figure and Axis

Next, we will create a figure and axis using the subplots() method. We will then plot two lines on the axis and add a legend to distinguish them.

fig, ax = plt.subplots()
ax.plot([1, 2, 3], 'ro-', label='easy as 1 2 3')
ax.plot([1, 4, 9], 'gs--', label='easy as 1 2 3 squared')
ax.legend()

Access Toolbar and VBox

We will access the toolbar and vbox attributes of the figure canvas manager using the manager.toolbar and manager.vbox methods, respectively.

manager = fig.canvas.manager
toolbar = manager.toolbar
vbox = manager.vbox

Add Button to Toolbar

We will add a button to the toolbar using the Gtk module. First, we create a button with a label and connect it to a function to print a message when clicked. Then, we create a toolitem, set its tooltip text, add the button to it, and insert it into the toolbar.

button = Gtk.Button(label='Click me')
button.show()
button.connect('clicked', lambda button: print('hi mom'))

toolitem = Gtk.ToolItem()
toolitem.show()
toolitem.set_tooltip_text('Click me for fun and profit')
toolitem.add(button)

pos = 8  ## where to insert this in the toolbar
toolbar.insert(toolitem, pos)

Add Label to VBox

We will add a label to the vbox to display the x,y coordinates of the mouse when it is dragged over the axis. First, we create a label with some text and add it to the vbox.

label = Gtk.Label()
label.set_markup('Drag mouse over axes for position')
label.show()
vbox.pack_start(label, False, False, 0)

Update Label Text on Mouse Movement

We will update the label text to display the x,y coordinates of the mouse when it is dragged over the axis. We create a function to update the label text and connect it to the motion_notify_event using the mpl_connect() method.

def update(event):
    if event.xdata is None:
        label.set_markup('Drag mouse over axes for position')
    else:
        label.set_markup(
            f'<span color="#ef0000">x,y=({event.xdata}, {event.ydata})</span>')

fig.canvas.mpl_connect('motion_notify_event', update)

Display the Plot

Finally, we display the plot using the show() method.

plt.show()

Summary

In this lab, we learned how to use Matplotlib to create and modify figure windows. We also explored how to customize the GUI by accessing the underlying GTK widgets. We added a button to the toolbar and a label to the vbox, and updated the label text on mouse movement. We also plotted two lines on an axis and added a legend to distinguish them.

Other Python Tutorials you may like