How can we run Matplotlib in Tkinter?

Python Matplotlib library is helpful in many applications for visualizing data and information in terms of graphs and plots. It is possible to run matplotlib in a Tkinter application by importing the library and using the TkAgg backend for interactive GUI integration.

To create a GUI application that uses matplotlib functions, we import the library using matplotlib.pyplot and use TkAgg backend that provides Tkinter user interface compatibility.

Required Imports

We need to import several modules to integrate matplotlib with Tkinter ?

from tkinter import *
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# Set the backend before creating any plots
matplotlib.use("TkAgg")

Basic Plot Example

Here's how to embed a matplotlib plot inside a Tkinter window ?

from tkinter import *
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# Set backend
matplotlib.use("TkAgg")

# Create Tkinter window
win = Tk()
win.geometry("700x400")
win.title("Matplotlib in Tkinter")

# Create matplotlib figure
figure = Figure(figsize=(6, 4), dpi=100)
plot = figure.add_subplot(1, 1, 1)

# Define data points
x = [0.2, 0.5, 0.8, 1.0]
y = [1.0, 1.2, 1.3, 1.4]

# Create the plot
plot.plot(x, y, color="red", marker="o", linewidth=2, label="Data Points")
plot.plot(0.5, 0.3, color="blue", marker="s", markersize=8, label="Single Point")

# Add labels and legend
plot.set_xlabel("X Axis")
plot.set_ylabel("Y Axis")
plot.set_title("Sample Plot")
plot.legend()
plot.grid(True)

# Create canvas and embed in Tkinter
canvas = FigureCanvasTkAgg(figure, win)
canvas.get_tk_widget().pack(fill=BOTH, expand=True)

win.mainloop()

Interactive Plot with Buttons

You can add buttons to update the plot dynamically ?

from tkinter import *
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np

matplotlib.use("TkAgg")

class PlotApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Interactive Plot")
        self.root.geometry("800x600")
        
        # Create figure
        self.figure = Figure(figsize=(8, 5), dpi=100)
        self.plot = self.figure.add_subplot(1, 1, 1)
        
        # Initial plot
        self.update_plot("sin")
        
        # Create canvas
        self.canvas = FigureCanvasTkAgg(self.figure, root)
        self.canvas.get_tk_widget().pack(fill=BOTH, expand=True)
        
        # Create buttons frame
        button_frame = Frame(root)
        button_frame.pack(pady=10)
        
        Button(button_frame, text="Sin Wave", command=lambda: self.update_plot("sin")).pack(side=LEFT, padx=5)
        Button(button_frame, text="Cos Wave", command=lambda: self.update_plot("cos")).pack(side=LEFT, padx=5)
        Button(button_frame, text="Random", command=lambda: self.update_plot("random")).pack(side=LEFT, padx=5)
    
    def update_plot(self, plot_type):
        self.plot.clear()
        x = np.linspace(0, 2*np.pi, 100)
        
        if plot_type == "sin":
            y = np.sin(x)
            self.plot.plot(x, y, 'b-', label='sin(x)')
        elif plot_type == "cos":
            y = np.cos(x)
            self.plot.plot(x, y, 'r-', label='cos(x)')
        else:
            y = np.random.random(100)
            self.plot.plot(y, 'g-', label='random')
        
        self.plot.set_title(f"{plot_type.capitalize()} Function")
        self.plot.legend()
        self.plot.grid(True)
        self.canvas.draw()

# Create and run the app
root = Tk()
app = PlotApp(root)
root.mainloop()

Key Components

Component Purpose Usage
matplotlib.use("TkAgg") Set backend Must call before creating plots
Figure Main plot container Create with specific size/DPI
FigureCanvasTkAgg Embed plot in Tkinter Links matplotlib to Tkinter widget
canvas.draw() Refresh plot Call after updating plot data

Conclusion

Matplotlib integrates seamlessly with Tkinter using the TkAgg backend. Use FigureCanvasTkAgg to embed plots in your GUI applications, and call canvas.draw() to refresh plots when data changes.

Updated on: 2026-03-25T22:20:11+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements