Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a matplotlib bar chart in Tkinter

I am trying to display a matplotlib bar chart in a Tkinter window. I have found plenty of tutorials on how to put a line chart in, such as this: http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html

But I can't find one for putting in a bar chart. The only way I know to make a bar chart is like this: http://matplotlib.org/examples/api/barchart_demo.html. Obviously, the modules imported in the bar chart example are not the same as the ones in the Tkinter examples, and I'm not sure how to make it work, if it can at all.

Long story short, can anyone provide me with an example of a matplotlib bar chart being displayed inside a Tkinter window? Thanks.

like image 223
Sam Krygsheld Avatar asked Feb 10 '23 12:02

Sam Krygsheld


1 Answers

For anyone who may be wondering in the future, I figured out how to get it to work. Basically, your bar chart has to be on a Figure so that FigureCanvasTkAgg can then generate a widget for Tkinter to use. I had assumed that you needed to use pyplot, which isn't true. This is what I came up with:

import matplotlib, numpy, sys
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = Tk.Tk()

f = Figure(figsize=(5,4), dpi=100)
ax = f.add_subplot(111)

data = (20, 35, 30, 35, 27)

ind = numpy.arange(5)  # the x locations for the groups
width = .5

rects1 = ax.bar(ind, data, width)

canvas = FigureCanvasTkAgg(f, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

Tk.mainloop()
like image 132
Sam Krygsheld Avatar answered Feb 12 '23 09:02

Sam Krygsheld