Summary: in this tutorial, you’ll learn how to display a graph from the Matplotlib library on a Tkinter application.
Display a bar chart from matplotlib in Tkinter applications #
Matplotlib is a third-party library for creating professional visualizations in Python. Since Matplotlib is a third-party library, you need to install it before use.
To install the matplotlib package, you can use the following pip command:
pip install matplotlibCode language: Python (python)The following program uses the matplotlib to create a bar chart that shows the top five programming languages by popularity.
import tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg,
NavigationToolbar2Tk
)
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title('Tkinter Matplotlib Demo')
# prepare data
data = {
'Python': 11.27,
'C': 11.16,
'Java': 10.46,
'C++': 7.5,
'C#': 5.26
}
languages = data.keys()
popularity = data.values()
# create a figure
figure = Figure(figsize=(6, 4), dpi=100)
# create FigureCanvasTkAgg object
figure_canvas = FigureCanvasTkAgg(figure, self)
# create the toolbar
NavigationToolbar2Tk(figure_canvas, self)
# create axes
axes = figure.add_subplot()
# create the barchart
axes.bar(languages, popularity)
axes.set_title('Top 5 Programming Languages')
axes.set_ylabel('Popularity')
figure_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
if __name__ == '__main__':
app = App()
app.mainloop()Code language: Python (python)Output: