2016-12-23 2 views
0

동적 그래프를 만들고 싶습니다. 그래프를 60 초마다 지우고 싶습니다만, cla()와 clf()로는 틀린 점이 무엇입니까? cla() 및 clf()를 사용하는 것을 제외하고 그래프를 지울 수있는 방법이 있습니까?그래프 tkinter를 지우는 법

#import lib client paho mqtt 
from Tkinter import * 
from ttk import * 
from datetime import datetime 
import matplotlib 
import paho.mqtt.client as mqtt 
import redis, time 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 
from matplotlib.figure import Figure 
from matplotlib import style 
import matplotlib.pyplot as plt 
from matplotlib.pyplot import get_current_fig_manager 

mqttc = mqtt.Client("serverclient",clean_session=False)#inisialisasi mqtt client 
r = redis.Redis("localhost",6379) 
start = time.time() 
date = datetime.now().strftime('%S') 
f = Figure(figsize=(5,4), dpi=100) 
a = f.add_subplot(111) 
b = f.add_subplot(111) 
style.use('ggplot') 
matplotlib.use("TkAgg") 
suhu=30 
cahaya=50 


def mqttx(): 
    #fungsi callback 
    def on_message(mqttc,obj,msg): 
     global LED1 
     global LED2 
     datasuhu = r.lrange("suhu",-1,-1) 
     datacahaya = r.lrange("cahaya",-1,-1) 
     print "Telah Diterima message : "+msg.payload+" topik "+msg.topic 
     r.rpush(msg.topic,msg.payload) 

    mqttc.on_message = on_message 

    mqttc.connect("localhost",1883) 

    mqttc.subscribe("suhu") 
    mqttc.subscribe("cahaya") 

class Example(Frame): 
    def __init__(self, parent): 
     Frame.__init__(self, parent) 
     self.parent = parent 
     self.initUI() 

     self.graph() 

    def initUI(self): 

     self.parent.title("Subcriber") 
     self.style = Style() 
     self.style.theme_use("default") 
     self.pack(fill=BOTH, expand=1) 

     self.xList1 = [] 
     self.yList1 = [] 
     self.canvas = FigureCanvasTkAgg(f, self) 

     self.canvas.show() 
     self.canvas.get_tk_widget().pack(expand=True) 
     thismanager = get_current_fig_manager() 
     thismanager.window.wm_geometry("+500+0") 


    def graph(self): 
     suhu1 = r.lrange("suhu",-1,-1) 
     cahaya1 = r.lrange("cahaya",-1,-1) 
     date = datetime.now().strftime('%S') 
     join1=str(''.join(suhu1)) 
     suhugraph=float(join1) 

     join2=str(''.join(cahaya1)) 
     cahayagraph=float(join2) 

     self.xList1.append(date) 
     self.yList1.append(suhugraph) 
     a.clear() 
     a.axis([0, 100, 0, 60]) 
     a.plot(self.xList1, self.yList1,"r-") 

     if date=="00" : 
      plt.clf() 
      plt.cla() 
     else: 

      self.canvas.draw() 

     self.after(1000, self.graph) 

def main(): 
    root = Tk() 
    root.geometry("1500x1400+300+300") 
    app = Example(root) 

    root.mainloop() 

if __name__ == '__main__': 

    mqttx() 
    mqttc.loop_start() 
    main() 
+0

BTW : 당신은 문자열로 초를 변환 할 필요가 없습니다 -'datetime.now() – furas

+0

을 '초' ''.join()를 사용하면'STR을 필요가 없습니다'문자열을 생성합니다()'. -'suhugraph = float (''. join (suhu1))' – furas

+0

@furas 오, 그래, 고마워.하지만 내 문제를 도와 줄 수있어? cant clear matplotlib figure/canvas here –

답변

0
당신이 self.xList1에서 데이터를 제거해야 명확한 그래프로

때문에 플롯 (a.clear()/plt.clf()/plt.cla()) 당신은 여전히 ​​목록에있는 데이터를 가지고 당신이 다시 그리기를 삭제 한 후 self.yList1

self.xList1 = [] 
self.yList1 = [] 

.

나는 Redis으로 코드를 실행할 수 없습니다 및 mqtt은 그래서 random

import matplotlib 
matplotlib.use("TkAgg") 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 

import matplotlib.pyplot as plt 
from matplotlib.figure import Figure 

import Tkinter as tk 
from datetime import datetime 

import random 

# --- classes --- (CamelCase names) 

class Example(tk.Frame): 

    def __init__(self, parent): 
     tk.Frame.__init__(self, parent) 
     # you don't need self.parent - tk.Frame sets self.master = parent   
     self.pack(expand=True, fill='both') # put frame inside Tk() window (and resize) 

     self.x_list_1 = [] 
     self.y_list_1 = [] 

     self.initUI() 

     self.draw() 

    def initUI(self): 
     self.fig = Figure(figsize=(5, 4), dpi=100) 
     self.a = self.fig.add_subplot(111) 
     self.a.axis((0, 100, 0, 60)) 

     self.canvas = FigureCanvasTkAgg(self.fig, self) 
     self.canvas.get_tk_widget().pack(expand=True, fill='both') 

    def draw(self): 

     date = datetime.now().strftime('%S') 
     suhugraph = random.randint(1, 60) 

     if date == "00": 
      self.a.clear() 
      self.a.axis((0, 100, 0, 60)) 
      self.x_list_1 = [] 
      self.y_list_1 = [] 

     self.x_list_1.append(date) 
     self.y_list_1.append(suhugraph) 

     self.a.plot(self.x_list_1, self.y_list_1, "r-") 
     self.canvas.draw() 

     self.after(1000, self.draw) 

# --- functions --- (lower_case names) 

def main(): 
    root = tk.Tk() 
    app = Example(root) 
    root.mainloop() 

# --- main --- 

if __name__ == '__main__': 
    main() 
BTW

과 버전을했다 : 크기 조정 후 응답에 관해서는 matplotlib: clearing a plot, when to use cla(), clf() or close()?


- 문제에서 두 개의 루프가 될 수 코드 : root.mainloop()이고 아마도 mqttc.loop_start()입니다. mqttc 코드를 실행할 수 없으므로 테스트 할 수 없습니다.


은 BTW : plot()clear()

우선없이 업데이트 플롯 당신은 당신이

self.line.set_xdata(self.x_list_1) 
self.line.set_ydata(self.y_list_1) 

그래서 당신은 '돈 라인에있는 모든 데이터를 대체

self.line, = self.a.plot([], [], "r-") 

나중에 빈 줄을 만들 clear()이 필요하고 축을 다시 설정하십시오.

import matplotlib 
matplotlib.use("TkAgg") 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 

import matplotlib.pyplot as plt 
from matplotlib.figure import Figure 

import Tkinter as tk 
from datetime import datetime 

import random 

# --- classes --- (CamelCase names) 

class Example(tk.Frame): 

    def __init__(self, parent): 
     tk.Frame.__init__(self, parent) 
     # you don't need self.parent - tk.Frame sets self.master = parent   
     self.pack(expand=True, fill='both') # put frame inside Tk() window (and resize) 

     self.x_list_1 = [] 
     self.y_list_1 = [] 

     self.initUI() 

     self.draw() 

    def initUI(self): 
     self.fig = Figure(figsize=(5, 4), dpi=100) 
     self.a = self.fig.add_subplot(111) 
     self.a.axis((0, 100, 0, 60)) 

     self.canvas = FigureCanvasTkAgg(self.fig, self) 
     self.canvas.get_tk_widget().pack(expand=True, fill='both') 

     # create empty line 
     self.line, = self.a.plot([], [], "r-") 

    def draw(self): 

     date = datetime.now().strftime('%S') 
     suhugraph = random.randint(1, 60) 

     if date == "00": 
      self.x_list_1 = [] 
      self.y_list_1 = [] 

     self.x_list_1.append(date) 
     self.y_list_1.append(suhugraph) 

     # update data in line without `plot()` (and without `clear()`) 
     self.line.set_xdata(self.x_list_1) 
     self.line.set_ydata(self.y_list_1) 

     self.canvas.draw() 

     self.after(1000, self.draw) 

# --- functions --- (lower_case names) 

def main(): 
    root = tk.Tk() 
    app = Example(root) 
    root.mainloop() 

# --- main --- 

if __name__ == '__main__': 
    main()