简体   繁体   中英

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.

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.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

Tk.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM