4

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.

1
  • Hi Sam, could you add what you've tried so far? It seems like you just need to have a go at bodging together the two links you've given, why not have a go! Commented Jul 21, 2015 at 21:47

1 Answer 1

8

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Apparently since ~2018, canvas.draw() has replaced canvas.show() -- I edited the code accordingly. See github.com/jarvisteach/appJar/issues/551

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.