如何使用Tkinter显示两个图形?

时间:2017-10-25 12:45:02

标签: python matplotlib tkinter

你好,我有一个代码,我想在同一个数字上显示我的两个图表。这是我的代码:

import Tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np

app = tk.Tk()
app.wm_title("Graphs")

fig = Figure(figsize=(6, 4), dpi=96)
a = np.array([1,2,3])
ax = fig.add_subplot(111)
bx = fig.add_subplot(111)
bx.plot(a,np.array([0,0.5,2]))


graph = FigureCanvasTkAgg(fig, master=app)
canvas = graph.get_tk_widget()
canvas.grid(row=0, column=0, rowspan = 11, padx =10, pady =5)

def updateScale(value):
   ax.clear()
   print "scale is now %s" % (value)
   #a = np.array([1, 2, 3])
   b = float(value)*a
   ax.plot(a,b)
   graph.show()

value = tk.DoubleVar()
scale = tk.Scale(app, variable=value, orient="horizontal",length = 100, from_=0.55, to=2.75, resolution = 0.01,command=updateScale)
scale.grid(row=0, column=1)

app.mainloop()

一切都没问题,除了我不看bx ......有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:1)

你不想在这里使用两个不同的子图。相反,你可以采用相同的轴来绘制。然后不要使用clear,因为它会破坏初始图表。而只是更新现有的行。如果line, = axp.plot()line.set_data()会将新数据设置到该行。然后重新缩放轴并绘制画布。

import Tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np

app = tk.Tk()
app.wm_title("Graphs")

fig = Figure(figsize=(6, 4), dpi=96)
a = np.array([1,2,3])
ax = fig.add_subplot(111)

line, = ax.plot(a,np.array([0,0.5,2]))
line2, = ax.plot(a,0.55*a)

graph = FigureCanvasTkAgg(fig, master=app)
canvas = graph.get_tk_widget()
canvas.grid(row=0, column=0, rowspan = 11, padx =10, pady =5)

def updateScale(value):
   print "scale is now %s" % (value)
   b = float(value)*a
   # set new data to the line
   line2.set_data(a,b)
   # rescale the axes
   ax.relim()
   ax.autoscale()
   #draw canvas
   fig.canvas.draw_idle()


value = tk.DoubleVar()
scale = tk.Scale(app, variable=value, orient="horizontal",length = 100, 
                 from_=0.55, to=2.75, resolution = 0.01,command=updateScale)
scale.grid(row=0, column=1)

app.mainloop()