【原】使用Tkinter繪製GUI並結合Matplotlib實現交互式繪圖

在數據分析的過程當中,每每須要對所創建的模型進行可視化,並調整其中的某些參數。python

一般狀況下,在Python中能夠經過Matplotlib來進行繪製圖像。然而該繪製過程是靜態的,也就是每次調整完參數須要從新調用繪圖語句進行繪圖展現。咱們的目標是結合GUI組件,實現對模型參數的交互式繪圖。這樣,能夠在展現出的GUI界面中動態的調整模型的參數,並繪製圖像。canvas

最終實現的效果以下:後端

4d2b174e-f75e-4430-9060-40360677a567

能夠經過GUI界面指定參數繪製散點圖。app

該過程須要結合Python的Tkinter庫來進行GUI部分的實現。代碼以下:dom

   1: #!/usr/bin/env python
   2: #coding:utf-8
   3: """
   4:   Author:  Chaos --<Chaosimpler@gmail.com>
   5:   Purpose: 修改Matplotlib的後端,實如今Tkinter的GUI繪製圖像
   6:   Created: 2014-10-15
   7: """
   8: import numpy as np
   9: from Tkinter import *
  10: import matplotlib
  11: from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
  12: from matplotlib.figure import Figure
  13:  
  14: #----------------------------------------------------------------------
  15: def drawPic():
  16:     """
  17:     獲取GUI界面設置的參數,利用該參數繪製圖片
  18:     """
  19:     
  20:     #獲取GUI界面上的參數
  21:     try:sampleCount=int(inputEntry.get())
  22:     except:
  23:         sampleCount=50
  24:         print '請輸入整數'
  25:         inputEntry.delete(0,END)
  26:         inputEntry.insert(0,'50')
  27:     
  28:     #清空圖像,以使得先後兩次繪製的圖像不會重疊
  29:     drawPic.f.clf()
  30:     drawPic.a=drawPic.f.add_subplot(111)
  31:     
  32:     #在[0,100]範圍內隨機生成sampleCount個數據點
  33:     x=np.random.randint(0,100,size=sampleCount)
  34:     y=np.random.randint(0,100,size=sampleCount)
  35:     color=['b','r','y','g']
  36:     
  37:     #繪製這些隨機點的散點圖,顏色隨機選取
  38:     drawPic.a.scatter(x,y,s=3,color=color[np.random.randint(len(color))])
  39:     drawPic.a.set_title('Demo: Draw N Random Dot')
  40:     drawPic.canvas.show()
  41:     
  42:     
  43: if __name__ == '__main__':
  44:     
  45:     matplotlib.use('TkAgg')
  46:     root=Tk()
  47:     
  48:     #在Tk的GUI上放置一個畫布,並用.grid()來調整佈局
  49:     drawPic.f = Figure(figsize=(5,4), dpi=100) 
  50:     drawPic.canvas = FigureCanvasTkAgg(drawPic.f, master=root)
  51:     drawPic.canvas.show()
  52:     drawPic.canvas.get_tk_widget().grid(row=0, columnspan=3)    
  53:  
  54:     #放置標籤、文本框和按鈕等部件,並設置文本框的默認值和按鈕的事件函數
  55:     Label(root,text='請輸入樣本數量:').grid(row=1,column=0)
  56:     inputEntry=Entry(root)
  57:     inputEntry.grid(row=1,column=1)
  58:     inputEntry.insert(0,'50')
  59:     Button(root,text='畫圖',command=drawPic).grid(row=1,column=2,columnspan=3)
  60:     
  61:     #啓動事件循環
  62:     root.mainloop()
相關文章
相關標籤/搜索