Matplotlib: Creating a Graph With Glade 3

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, you will learn how to create a simple graph using Matplotlib with Glade 3. Matplotlib is a plotting library for the Python programming language and can be used to create a wide variety of graphs and visualizations.

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/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/custom_backends("`Custom Backends`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") 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-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} matplotlib/figures_axes -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} matplotlib/line_plots -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} matplotlib/custom_backends -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/variables_data_types -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/strings -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/type_conversion -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/conditional_statements -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/lists -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/tuples -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/function_definition -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/importing_modules -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/using_packages -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/standard_libraries -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/classes_objects -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/encapsulation -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/numerical_computing -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/data_visualization -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} python/build_in_functions -.-> lab-48831{{"`Matplotlib: Creating a Graph With Glade 3`"}} end

Setting up the Environment

Before we start creating our graph, we need to set up the environment. Open your terminal and create a new Python file called mpl_with_glade3.py. Make sure you have installed the required libraries: matplotlib, numpy, gi, and Gtk.

Creating a Glade 3 File

Next, we will create a Glade 3 file to create the user interface for our application. Open Glade 3 and create a new project. Add a ScrolledWindow widget and a Window widget. Name the window window1 and the scrolled window scrolledwindow1. Save the file as mpl_with_glade3.glade.

Creating the Graph

Now we can start creating our graph. First, import the necessary libraries and define the Window1Signals class. This class will handle the destroy signal for the window.

from pathlib import Path

import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

import numpy as np

from matplotlib.backends.backend_gtk3agg import \
    FigureCanvasGTK3Agg as FigureCanvas
from matplotlib.figure import Figure


class Window1Signals:
    def on_window1_destroy(self, widget):
        Gtk.main_quit()

Defining the Main Function

Next, define the main() function. This function will create the user interface, create the graph, and display the window.

def main():
    builder = Gtk.Builder()
    builder.add_objects_from_file(
        str(Path(__file__).parent / "mpl_with_glade3.glade"),
        ("window1", ""))
    builder.connect_signals(Window1Signals())
    window = builder.get_object("window1")
    sw = builder.get_object("scrolledwindow1")

    ## Start of Matplotlib specific code
    figure = Figure(figsize=(8, 6), dpi=71)
    axis = figure.add_subplot()
    t = np.arange(0.0, 3.0, 0.01)
    s = np.sin(2*np.pi*t)
    axis.plot(t, s)

    axis.set_xlabel('time [s]')
    axis.set_ylabel('voltage [V]')

    canvas = FigureCanvas(figure)  ## a Gtk.DrawingArea
    canvas.set_size_request(800, 600)
    sw.add(canvas)
    ## End of Matplotlib specific code

    window.show_all()
    Gtk.main()

if __name__ == "__main__":
    main()

Running the Application

Save the file and run it using the terminal command python mpl_with_glade3.py. The window with the graph should appear.

Summary

Congratulations! You have successfully created a graph using Matplotlib with Glade 3. You can use this as a starting point to create more complex graphs and visualizations.

Other Python Tutorials you may like