How to Insert a Matplotlib Plot into a Tkinter Program

Posted by


Matplotlib is a powerful Python library that is used for creating a variety of plots and graphs. Tkinter is a popular GUI toolkit for creating desktop applications in Python. In this tutorial, we will learn how to embed a Matplotlib graph into a Tkinter application.

Step 1: Install Matplotlib and Tkinter
Before we begin, make sure that you have Matplotlib and Tkinter installed on your system. You can install Matplotlib using pip by running the following command in your terminal:

pip install matplotlib

Tkinter is included with Python by default, so you do not need to install it separately.

Step 2: Create a basic Tkinter application
To get started, let’s create a basic Tkinter application with a blank canvas where we will embed our Matplotlib graph. Open a new Python file and add the following code:

import tkinter as tk

root = tk.Tk()
root.title("Embedding Matplotlib in Tkinter")

canvas = tk.Canvas(root, width=800, height=600)
canvas.pack()

root.mainloop()

Save the file as app.py and run it. You should see a blank window with the title "Embedding Matplotlib in Tkinter".

Step 3: Create a Matplotlib graph
Next, let’s create a Matplotlib graph that we will embed into our Tkinter application. Add the following code to your app.py file:

import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

root = tk.Tk()
root.title("Embedding Matplotlib in Tkinter")

fig = Figure(figsize=(6, 4), dpi=100)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()

root.mainloop()

Save the file and run it. You should see a basic Matplotlib graph displayed in the Tkinter window.

Step 4: Customize the Matplotlib graph
You can customize the Matplotlib graph by adding titles, labels, legends, and other elements. Here’s an example:

import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

root = tk.Tk()
root.title("Embedding Matplotlib in Tkinter")

fig = Figure(figsize=(6, 4), dpi=100)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
ax.set_title('Sample Plot')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.legend(['Line 1'], loc='upper left')

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()

root.mainloop()

Save the file and run it to see the updated Matplotlib graph with titles, labels, and a legend.

Step 5: Add interactive elements to the Tkinter application
You can add interactive elements to your Tkinter application that will update the Matplotlib graph dynamically. Here’s an example where we add a button that changes the data plotted on the graph when clicked:

import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def update_data():
    ax.clear()
    ax.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1])
    ax.set_title('Updated Plot')
    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')
    ax.legend(['Line 2'], loc='upper left')
    canvas.draw()

root = tk.Tk()
root.title("Embedding Matplotlib in Tkinter")

fig = Figure(figsize=(6, 4), dpi=100)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
ax.set_title('Sample Plot')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.legend(['Line 1'], loc='upper left')

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()

update_button = tk.Button(root, text="Update Data", command=update_data)
update_button.pack()

root.mainloop()

Save the file and run it to see the Matplotlib graph with a button that updates the data when clicked.

Congratulations! You have successfully embedded a Matplotlib graph into a Tkinter application. Feel free to explore more customization options and interactive elements to create powerful data visualization tools in Python.

0 0 votes
Article Rating
21 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jerryhuang7194
29 days ago

It's reassuring to know that I'm not the only one who wants to embed Matplotlib into Tkinter! 🥲

@baghdadiabdellatif1581
29 days ago

Thank you

@АндрейБабаш-ю9п
29 days ago

👍👍👍

@JavierSalazar-i4f
29 days ago

Quite useful, thank you for sharing such knowledge

@carrocesta
29 days ago

very nice, thanks a lot dude! greetings from Spain 🙂

@tanvirahmed8586
29 days ago

Thanks man! That really helped me a lot.

@vilmoskocsis3064
29 days ago

exactly what I need!

@rishabhagnihotri6004
29 days ago

Perfect brother!!

@tuananh5987
29 days ago

How to create multiple graph on specific window by clicking a button of Tkinter?

@andrikurniawan823
29 days ago

great job buddy, Thank you for sharing

@naderbazyari2
29 days ago

Many many thanks for such a short and concise video. much appreciated

@BrianSwatton
29 days ago

Very helpful, thanks

@spourabbas
29 days ago

Thanks. very helpful

@kychemclass5850
29 days ago

Where is the data of the random points stored? The old random points were remembered and displayed when "Plot Graph" is clicked so they must be getting stored somewhere.

@HolyPiyush
29 days ago

Sir can you tell how to do same thing with plotly module
thank you

@JurinoH
29 days ago

How can I change canvas size ? I need smaller canvas and graph. Thanks

@kychemclass5850
29 days ago

Excellent. Thank you for sharing your knowledge. Could I suggest a follow-up video whereby the matplotlib graph is animated?

@LowcountryLightworking
29 days ago

Extremely helpful… Thank you for taking the time to make this!

@darshanb
29 days ago

I need to convert a python program source code to its exe using pyinstaller or auto py to exe but it always gives me error while converting of modules not found using–one file option
Using–one dir the exe works

Can you help me out

I am actually trying to convert an open source app available on github need to modify it and pack it back again into exe

@ReinventedWeb
29 days ago

Nice