简体   繁体   English

在Tkinter中显示matplotlib条形图

[英]Displaying a matplotlib bar chart in Tkinter

I am trying to display a matplotlib bar chart in a Tkinter window. 我试图在Tkinter窗口中显示matplotlib条形图。 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 我找到了很多关于如何放置折线图的教程,例如: 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 . 我知道制作条形图的唯一方法是这样的: 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. 显然,条形图示例中导入的模块与Tkinter示例中的模块不同,如果可以的话,我不知道如何使其工作。

Long story short, can anyone provide me with an example of a matplotlib bar chart being displayed inside a Tkinter window? 长话短说,任何人都可以向我提供一个在Tkinter窗口内显示的matplotlib条形图的示例吗? 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. 基本上,您的条形图必须在图上,以便FigureCanvasTkAgg可以生成Tkinter要使用的小部件。 I had assumed that you needed to use pyplot, which isn't true. 我原以为你需要使用pyplot,这不是真的。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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