本文介绍在wxpython中加入matplotlib图表
#coding=utf-8
import wx
import numpy
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas #FigureCanvasWxAgg
from matplotlib.figure import Figure
import matplotlib
class MyFrame(wx.Frame):
def __init__(self,user,parent,size=(900, 700)):
self.user=user
super(MyFrame,self).__init__(parent,title="主窗口_"+user,size=size)
self.panel=MyPanel(self) #MyPanel实例
class MyPanel(wx.Panel):
def __init__(self,parent):
super(MyPanel,self).__init__(parent)
self.locale = wx.Locale(wx.LANGUAGE_CHINESE_SIMPLIFIED)
scores = [89, 98, 70, 80, 60, 78, 85, 90]
sum = 0
for s in scores:
sum += s
average = sum / len(scores)
t_score = numpy.arange(1, len(scores) + 1, 1)
s_score = numpy.array(scores)
self.f= Figure(figsize=(12,10),dpi=100, tight_layout=True, facecolor="WhiteSmoke") #Figure()#WhiteSmoke
matplotlib.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文
matplotlib.rcParams['axes.unicode_minus']=False
self.sub = self.f.add_subplot(2,2,1,title="折线图1",xlabel="成绩",ylabel="数量")
self.sub.plot(t_score, s_score, 'ro', t_score, s_score, 'k')
self.sub.axhline(y=average, color='r')
self.sub.grid(True)
self.sub.set_xlabel('T')
self.sub.set_ylabel('score')
self.sub = self.f.add_subplot(2,2,2,title="折线图2",xlabel="成绩",ylabel="数量")
self.sub.plot(t_score, s_score, 'ro', t_score, s_score, 'k')
self.sub.axhline(y=average, color='r')
self.sub.grid(True)
self.sub.set_xlabel('T')
self.sub.set_ylabel('score')
self.sub = self.f.add_subplot(2,2,3,title="折线图3",xlabel="成绩",ylabel="数量")
self.sub.plot(t_score, s_score, 'ro', t_score, s_score, 'k')
self.sub.axhline(y=average, color='r')
self.sub.grid(True)
self.sub.set_xlabel('T')
self.sub.set_ylabel('score')
self.sub = self.f.add_subplot(2,2,4,title="折线图4",xlabel="成绩",ylabel="数量")
self.sub.plot(t_score, s_score, 'ro', t_score, s_score, 'k')
self.sub.axhline(y=average, color='r')
self.sub.grid(True)
self.sub.set_xlabel('T')
self.sub.set_ylabel('score')
canvas=FigureCanvas(self,-1 , self.f)
canvas.draw()
b1 = wx.Button(self, label="返回")
self.Bind(wx.EVT_BUTTON, self.Back, b1)
box = wx.BoxSizer(wx.VERTICAL)
box.Add(canvas,0, wx.ALL|wx.EXPAND, 0)
box.Add(b1, proportion=0, border=3, flag=wx.ALL)
self.SetSizer(box)
def Back(self, evt):
pass
if __name__ == "__main__":
app=wx.App() #创建App类的实例
frame=MyFrame("usertest",parent=None)
frame.Show()
app.MainLoop() #调用MainLoop()主循环方法