无法获得直方图(matplotlib.pyplot.hist)来更新tkinter中的新数据

时间:2017-09-13 23:54:00

标签: python matplotlib tkinter histogram

我在python中使用tkinter和matplotlib制作一个gui。它显示分布在多个笔记本选项卡上的数据和图形。当用户进行某些选择时,图形和文本会更新。一切都很完美,直到我添加了直方图。我不知道如何更改其数据或xlim和ylim。

下面的代码是我的代码的摘录,以展示它是如何工作的。

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

root = tk.Tk()
root.geometry('1200x300')

def configFrame(frame, num=50):
  for x in range(num):
    frame.rowconfigure(x, weight=1)
    frame.columnconfigure(x, weight=1)

def runProg():
  mu, sigma = 0, .1
  y = np.array(np.random.normal(mu, sigma, 100))
  x = np.array(range(100))

  lines2[1].set_xdata(x)
  axs2[1].set_xlim(x.min(), x.max()) # You need to change the limits manually

  # I know the y isn't changing in this example but I put it in for others to see
  lines2[1].set_ydata(y)
  axs2[1].set_ylim(y.min(), y.max())

  canvas2.draw()

configFrame(root)

nb = ttk.Notebook(root)
# This just creates a blamk line
nb.grid(row=1, column=0, columnspan=2, rowspan=2, sticky='NESW')

myPage = ttk.Frame(nb)
configFrame(myPage)
nb.add(myPage, text="My page")

myFrame = ttk.Frame(myPage)
myFrame.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')
configFrame(myFrame)

# There is another figure on another tab
fig2 = Figure(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='k')

canvas2 = FigureCanvasTkAgg(fig2, master=myFrame)
canvas2._tkcanvas.grid(row=2, column=0, columnspan=50, rowspan=47, sticky='NESW')

axs2 = []
lines2=[]

# There are 4 other plots on page
axs2.append(fig2.add_subplot(4,1,1))

mu, sigma = 0, .1
y = list(np.random.normal(mu, sigma, 100))
x = list(range(100))
# the histogram of the data
n, bins, patches = axs2[0].hist(y, 25, normed=False)
axs2[0].set_xlabel('x Label')
axs2[0].set_ylabel('Y Label')
axs2[0].grid(True)
lines2.append([]) # Don't know how to access it from histogram

axs2.append(fig2.add_subplot(4,1,2))
lines, = axs2[1].plot(x,y)
lines2.append(lines)

fig2.canvas.draw()

runButton = tk.Button(myPage, text="Change Data", width=15, command=runProg)
runButton.grid(row=50, column=25, sticky='NW')
root.update()

root.mainloop()

1 个答案:

答案 0 :(得分:0)

好的,我能够通过清除轴并重新创建它来实现我想要的效果。它不是非常pythonic但似乎我不能改变.hist的数据。任何其他建议都赞赏,但这是有效的。

我所做的唯一改变是runProg()方法。我在下面提供了代码。

def runProg():
  mu, sigma = 0, .1
  y = np.array(np.random.normal(mu, sigma, 100))
  x = np.array(range(100))

  # It'a not really python but I just cleared the axis and remadeit
  axs2[0].cla()
  n, bins, patches = axs2[0].hist(y, 25, normed=False)
  axs2[0].set_xlabel('x Label')
  axs2[0].set_ylabel('Y Label')
  axs2[0].grid(True)
  #

  axs2[1].set_xlim(x.min(), x.max()) # You need to change the limits manually

  # I know the y isn't changing in this example but I put it in for others to see
  lines2[1].set_ydata(y)
  axs2[1].set_ylim(y.min(), y.max())

  canvas2.draw()