Open In App

Modify the Navigation Toolbar in a Matplotlib

Last Updated : 25 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Let us take a simple example of how it works. Suppose you have some data representing the x and y coordinates of points, and you want to create a line plot to visualize the relationship between them. Before moving let’s understand some of the Python Module.

  • sys: This module provides access to some variables used or maintained by the interpreter and functions that interact with the Python runtime.
  • matplotlib.pyplot: This module provides a MATLAB-like interface for creating plots and visualizations.
  • PyQt5.QtWidgets: This module provides the graphical components(widgets) needed for creating GUI applications.

Required Library

import matplotlib.pyplot as plt

Modify the Navigation Toolbar easily in a Matplotlib

Initially, you import the necessary parts of the Matplotlib library. Then, you provide the data points for the x and y axes and use the plot() function to create the line plot. You can add labels to the axes and a title to the plot for better understanding. Finally, you use show() to display the plot.

Creating Simple Line Graph

Now you can simply create the line graph as shown below.

Python3




x=[1,2,3,4,5]
y=[2,4,6,8,10]
 
#create a line plot
plt.plot(x,y)
 
#add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('line plot')
 
#show the plot
plt.show()


Output:

download

Metplotlib is a versatile library, and you can use it alongside other popular Python libraries like Pandas and Seaborn to create more advanced and insightful visualizations for your data analysis needs. In a nutshell, Matplotlib is a powerful tool for data visualization in Python, and it is widely used in various fields, including scientific research, data analysis, and more, making it an essential tool for anyone dealing with data visualization.

Customize the Navigation Toolbar in Matplotlib

The navigation toolbar is a user interface component in Matplotlib that provides interactive controls and tools for navigating and manipulating plots. it appears above or below the plot area and allows users to interact with the plot. The navigation toolbar typically includes several buttons and tools, each with specific functionality:

  1. Home: This button resets the plot to its original state, showing the entire dataset without any zooming or panning.
  2. Back and Forward: These buttons allow users to navigate backward and forward through the view history, which means they can undo or redo zooming and panning actions.
  3. Pan: The pan tool allows users to move the plot around by clicking and dragging. This is useful for exploring specific regions of the plot.
  4. Zoom: The zoom tool enables users to zoom in on a specific region of the plot by clicking and dragging a rectangle around the area of interest.
  5. Save: This button allows users to save the current plot as an image file for later use or inclusion in reports or presentations.
  6. Configure Subplots: This tool lets users adjust the arrangement and properties of subplots in a figure that contains multiple plots.
  7. Custom Tools: The navigation toolbar may include additional custom tools depending on the specific application or user requirements. These tools can be implemented to provide specific functionalities like data selection, annotation, or interaction.

Example: Here, we will try to understand Customize the Navigation Toolbar in Matplotlib with an example, the detailed explanation is given below.

Python3




import sys
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QComboBox
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
 
class CustomToolbar(NavigationToolbar):
    def __init__(self, canvas, parent=None):
        super(CustomToolbar, self).__init__(canvas, parent)
 
        # Add "Graph Type" drop-down menu
        graph_types = ["Line Graph", "Bar Chart", "Scatter Plot"]
        self.graph_type_combobox = QComboBox(self)
        self.graph_type_combobox.addItems(graph_types)
        self.graph_type_combobox.currentIndexChanged.connect(self._on_graph_type_selected)
        self.addWidget(self.graph_type_combobox)
 
    def _on_graph_type_selected(self):
        # Create a new graph based on the selected type from the drop-down menu
        graph_type = self.graph_type_combobox.currentText()
        fig = self.canvas.figure
        n_plots = len(fig.get_axes())
 
        for ax in fig.get_axes():
            ax.remove()
 
        # Set the subplot grid to 1 row and 1 column
        n_new_rows, n_new_cols = 1, 1
 
        if graph_type == "Line Graph":
            new_ax = fig.add_subplot(n_new_rows, n_new_cols, 1)
            new_ax.plot([1, 2, 3], [4, 2, 6], color='blue'# Set color to blue
            new_ax.set_title('Line Graph')
 
        elif graph_type == "Bar Chart":
            new_ax = fig.add_subplot(n_new_rows, n_new_cols, 1)
            bars = new_ax.bar(['A', 'B', 'C'], [3, 7, 2], color=['red', 'green', 'blue'])  # Set colors to red, green, and blue
            new_ax.set_title('Bar Chart')
 
        elif graph_type == "Scatter Plot":
            new_ax = fig.add_subplot(n_new_rows, n_new_cols, 1)
            new_ax.scatter([1, 2, 3], [4, 2, 6], color='orange'# Set color to orange
            new_ax.set_title('Scatter Plot')
 
        fig.canvas.draw()
 
def plot_example():
    # Create the initial figure and axis with increased figsize
    fig, ax = plt.subplots(figsize=(10, 6))
 
    # Data for the initial line graph
    x_line = [1, 2, 3, 4]
    y_line = [1, 4, 2, 3]
    ax.plot(x_line, y_line, label='Line Graph 1', color='red'# Set color to blue
 
    # Set the title, labels, and legend for the initial plot
    ax.set_title('Line Graph 1')
    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')
    ax.legend()
 
    # Create a QApplication and QMainWindow for the custom toolbar
    apps = QApplication(sys.argv)
    main_window = QMainWindow()
    main_window.setWindowTitle("Custom Navigation Toolbar")
    main_window.setGeometry(100, 100, 800, 600# Set window size
 
    # Create the central widget and layout
    central_widget = QWidget(main_window)
    layout = QVBoxLayout(central_widget)
 
    # Create a custom toolbar with the "Graph Type" drop-down menu
    canvas = FigureCanvas(fig)
    custom_toolbar = CustomToolbar(canvas, main_window)
    layout.addWidget(canvas)
    layout.addWidget(custom_toolbar)
 
    # Set the central widget and show the main window
    main_window.setCentralWidget(central_widget)
    main_window.show()
 
    # Run the Qt event loop
    sys.exit(apps.exec_())
 
# Call the function to create and show the plot with the custom toolbar
plot_example()


Output:Screenshot-(1085)

Code Explanation

A custom toolbar class ‘CustomToolbar‘ is defined:

  • This class inherits from NavigationToolbar, allowing us to extend its functionality.
  • The class initializes the navigation tools and adds a “Graph Type” drop-down menu with options for “Line Graph”, “Bar Chart”, and “Scatter Plot”.
  • When the user selects a graph type from the drop-down menu, it triggers the ‘_on_graph_type_selected’ method to create the corresponding graph.

The ‘_on_graph_type_selected’ method:

  • This method is called when the user selects a graph type from the drop-down menu.
  • It reads the selected graph type and clears the existing axes in the figure.
  • It then creates a new axis(new_ax) based on the selected graph type and adds it to the figure.
  • For “Line Graph,” plots a line graph with data[1,2,3] on the x-axis and [4,2,6] on the y-axis with a blue color.
  • For “Bar Graph,” plots a bar chart with data[A, B, C] on the x-axis and [3,7,2] on the y-axis with red, green, and blue bars respectively.
  • For “Scatter Plot,” plots a Scatter Plot with data[1,2,3] on the x-axis and [4,2,6] on the y-axis with orange makers.

The ‘plot_example’ function:

  • This function creates the initial figure and axis using ‘plt.subplots’ with a specified size(10*6).
  • It sets the data for the initial line graph and customizes the title, labels, and legends.
  • Then, it creates a PyQt5 application, sets up the main window, and creates a custom toolbar using the CustomToolbar class.
  • The figure is embedded in the main window using ‘FigureCnvas’, and the custom toolbar is added to the layout.
  • Finally, the application is executed by running the Qt event loop with ‘apps.exes_()’.

When you run the script, it will display a PyQt5 window containing the initial line graph with a drop-down menu. You can see the drop-down menu to switch between different graph types (line graph, bar chart, scatter plot), and the corresponding graph will be displayed in the same figure area with the navigation tools(zoom, pan, etc) provided by the NavigationToolbar2QT.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads