Python实现多子图绘制系统的示例详解

 更新时间:2023年09月02日 10:32:40   作者:微小冷  
这篇文章主要介绍了如何利用python实现多子图绘制系统,文中的示例代码讲解详细,具有一定的的参考价值,感兴趣的小伙伴可以跟随小编一起学习一下

Python绘图系统:python使用tkinter打造三维绘图系统的示例代码_python_脚本之家 (jb51.net)

图表类型和风格:极坐标绘图|散点图和条形图|混合类型图表

修改DrawType

之前在添加DrawType控件的时候,不仅添加了全局控件,而且每个AxisList也都添加了,这可不是乱添加的,而是为了后续的功能,即子图绘制。如果一个窗口中有多组坐标轴,那么每个坐标轴都应该有相应的图像。

这个显然属于绘图类型的范畴,所以第一步还是更新DrawType类,添加一个sub参数,用以约束子图的位置

def __init__(self, master, types, slctType, 
        sub='111', slctDim="xyz", slctProj='3d',
        ws=None, func=None, **options):

尽管添加的组件类型不同,但创建流程都是一样的,先改initVar,然后在initWidgets中添加Entry控件。

def initVar(self, sub, slctType, dim, proj):
    self.drawSub = tk.StringVar()
    self.drawSub.set(sub)
    # ....
    # 后面是类型、维度、投影
def initWidgets(self, ws, sub):
    if ws==None: ws = [5, 5, 5, 3]
    eny = ttk.Entry(self, width=ws[0], textvariable=self.drawSub)
    eny.pack(side=tk.LEFT, padx=2)
    # ...
    # 注意后面创建combobox时ws后移

然后再给出一个get函数

def getSub(self):
    return self.drawSub.get()

而且对应AxisList中也要添加get函数

def getSub(self):
    return self.drawTypeDim.getSub()

另外,需要补上之前未添加的getProj函数

def getProj(self):
    return self.drawTypeDim.getProj()

initVar中,几乎出现了4行一摸一样的代码,为了让其更加简洁,可以稍作修改

def initVar(self, sub, slctType, dim, proj):
    kv = {"sub":sub, "type":slctType, "dim":dim, "proj": proj}
    self.drawVars = {key:tk.StringVar() for key in kv}
    for key in drawVars:
        drawVars[key].set(kv[key])

然后把之前的注入self.drawSub, self.drawType, self.drawDim, self.drawProj等变量,均改写为self.drawVars字典调用的形式。类似getSub之类的函数非常容易修改,只要替换一下即可。而initWidgets,则和initVar一样,可以写得更加精简,具体改动较多,这里旧不贴代码了。

这里小小地声明一下,这种极致缩短代码行数的写法,在团队协作的时候并不提倡。

DrawType的调用逻辑

这一步比较繁琐,可以跳过。但文末附上的源代码中是做了这一步的更改的。

到目前为止,在DrawType中,最核心的四个参数就是子图类别、绘图类型、数据维度以及投影。换言之,只要有了这四个参数,那么理论上就可以得到一个DrawType的对象。

在DrawSystem中,除了每个AxisList有其自身的DrawType之外,还有一个全局的DrawType,但现在这两者之间并没有任何联系。一个比较好的设计逻辑是,新建AxisList的时候,以全局的DrawType为模板。

所以,可将这四个参数写成一个字典,用于参数的传递。所以首先在DrawType类中添加函数

def getDct(self):
    return {key:self.drawVars[key].get() for key in self.drawVars}

然后修改其初始化参数

def __init__(self, master, types, 
    varDct = {"sub":"111", "type":'点线图', "dim":"xyz", "proj": "3d"},
    ws=None, func=None, **options):

相应地更改initVar

def initVar(self, varDct):
    self.drawVars = {key:tk.StringVar() for key in varDct}
    for key in self.drawVars:
        self.drawVars[key].set(varDct[key])

这个改动导致接口发生变化,更要命的是AxisList的初始化参数也要传给DrawType,所以牵一发而动全身,包括AxilList以及DrawSystem,所有涉及到的代码都要修改。

绘图逻辑

由于每个子图都有其自身的坐标轴,为了让绘图井然有序,需要来一个全局的坐标轴字典,并在坐标轴设置函数中调用

def setDrawAxis(self, al):
    sub = int(al.getSub())
    print(sub)
    if sub in self.axDct:
        return self.axDct[sub]
    p = al.getProj() 
    if p == "None":
        self.axDct[sub] = self.fig.add_subplot(sub)
    else:
        self.axDct[sub] = self.fig.add_subplot(sub, projection=p)
    return self.axDct[sub]

绘图函数为

def btnDrawImg(self):
    self.fig.clf()
    keys = self.drawTypeDim.getDim()
    self.axDct = {}
    for al in self.als:
        ax = self.setDrawAxis(al)
        data = self.readDatas(al)
        draw = self.drawDct[al.getDrawType()]
        draw(ax, data, keys)
    self.fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.08)
    self.canvas.draw()

最后效果如下

源代码

import tkinter as tk
import tkinter.ttk as ttk
from tkinter.filedialog import askopenfilename
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import numpy as np
class AxisFrame(ttk.Frame):
    # widths 是每个控件的宽度
    def __init__(self, master, label, mode, widths, **options):
        super().__init__(master, **options)
        self.pack()
        self.label = label
        self.initVar(mode)
        self.initWidgets(widths)
    def initVar(self, mode):
        self.MODES = ("序列化", "源代码", "外部导入", "无数据")
        self.mode = tk.StringVar()
        self.setMode(mode)
    def initWidgets(self, widths):
        tk.Label(self, text=self.label, width=widths[0]).pack(side=tk.LEFT)
        self.slct = ttk.Combobox(self, width=widths[1], textvariable=self.mode)
        self.slct['value'] = self.MODES
        self.slct.pack(side=tk.LEFT)
        self.entry = tk.Entry(self, width=widths[2])
        self.entry.pack(padx=5, side=tk.LEFT, fill=tk.X)
    def setText(self, text):
        self.entry.delete(0, "end")
        self.entry.insert(0, text)
    def get(self):
        return self.entry.get()
    def setMode(self, mode):
        if type(mode) != str:
            mode = self.MODES[mode]
        self.mode.set(mode)
    def setData(self, data=None, **txyz):
        if self.mode.get() == "序列化":
            return self.getArray()
        elif self.mode.get() == "外部导入":
            return self.loadData(data)
        else:
            return self.readPython(**txyz)
    def readPython(self, t=None, x=None, y=None, z=None):
        self.data = eval(self.get())
        return self.data
    def loadData(self, data):
        if type(data) != type(None):
            self.data = data
        return self.data
    def getArray(self):
        val = self.get()
        self.data = eval(f"np.linspace({val})")
        return self.data
class AxisList(ttk.Frame):
    def __init__(self, master, 
        title, mode, widths, 
        types, typeDct,        # 绘图类型Combobox的参数
        **options):
        super().__init__(master, **options)
        self.pack()
        self.afs = {}
        self.data = {}
        self.initWidgets(title, widths)
        self.initFeature(types, typeDct)
        self.initAxis(mode, widths)
    def initWidgets(self, title, widths):
        self.btn = ttk.Button(self, text=title, width=sum(widths)+5,
            command=self.Click)
        self.btn.pack(side=tk.TOP, fill=tk.X, expand=tk.YES)
        self._c = ttk.Frame(self)
        self.collapsed = True
        self.Click()
    def initFeature(self, types, typeDct):
        frm = ttk.Frame(self._c)
        frm.pack(pady=2, side=tk.TOP, fill=tk.X)
        ttk.Button(frm, text="加载",width=5,
            command=self.btnLoadData).pack(side=tk.LEFT)
        self.drawTypeDim = DrawType(frm, types, typeDct, 
            func=self.dimChanged)
        self.drawTypeDim.pack(side=tk.LEFT, padx=2)
        self.vis = {L : True for L in 'txyz'}
    def dimChanged(self, evt):
        txyz = self.getDrawDim()
        for flag in 'txyz':
            self.vis[flag] = flag in txyz
        self.updateVisible()
    def updateVisible(self):
        for flag in 'txyz':
            self.afs[flag].pack_forget()
        for flag in 'txyz':
            if self.vis[flag]:
                self.afs[flag].pack(side=tk.TOP, fill=tk.X)
    def getSub(self):
        return self.drawTypeDim.getSub()
    def getProj(self):
        return self.drawTypeDim.getProj()
    def getDrawType(self):
        return self.drawTypeDim.getType()
    def getDrawDim(self):
        return self.drawTypeDim.getDim()
    def initAxis(self, mode, widths):
        for flag in 'txyz':
            self.afs[flag] = AxisFrame(self._c, flag, mode, widths)
            self.afs[flag].pack(side=tk.TOP, fill=tk.X)
        self.vis = {L : L in self.getDrawDim() for L in 'txyz'}
        self.updateVisible()
    def btnLoadData(self):
        name = askopenfilename()
        data = np.genfromtxt(name)
        for i, flag in enumerate('xyz'):
            if i >= data.shape[1]:
                return
            self.setOneMode(flag, "外部导入")
            self.data[flag] = self.setData(flag, data[:,i])
    def Click(self):
        if self.collapsed:
            self._c.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)            
        else:
            self._c.pack_forget()
        self.collapsed = not self.collapsed
    def setData(self, flag, data=None, **options):
        return self.afs[flag].setData(data, **options)
    def setOneMode(self, flag, mode):
        self.afs[flag].setMode(mode)
# 绘图类型和维度
# varDct 的格式是 {"sub":sub, "type":slctType, "dim":dim, "proj": proj}
class DrawType(ttk.Frame):
    # ws为两个combobox的宽
    def __init__(self, master, types, 
        varDct = {"sub":"111", "type":'点线图', "dim":"xyz", "proj": "3d"},
        ws=None, func=None, **options):
        super().__init__(master, **options)
        self.pack()
        self.dimChanged = func
        self.initVar(varDct)
        self.initWidgets(ws, types)
    def initVar(self, varDct):
        self.drawVars = {key:tk.StringVar() for key in varDct}
        for key in self.drawVars:
            self.drawVars[key].set(varDct[key])
    def initWidgets(self, ws, types):
        if ws==None: ws = [5, 5, 5, 3]
        slctDct = {'type':types, 
            'proj': ("None", "3d", "polar"), 
            'dim' : ("x", "xy", "xyz", "tx", "txy", "txyz")}    # 绘图维度
        keys = ['sub', 'type', 'proj', 'dim']
        wDct = {}  # 控件字典
        # 此为设置子图的Entry控件
        wDct['sub'] = ttk.Entry(self, width=ws[0], 
            textvariable=self.drawVars['sub'])
        for i, key in enumerate(keys[1:], 1):
            wDct[key] = ttk.Combobox(self, width=ws[i], 
                textvariable=self.drawVars[key])
            wDct[key]['value'] = slctDct[key]
        for key in keys:
            wDct[key].pack(side=tk.LEFT, padx=2)
        wDct['dim'].bind('<<ComboboxSelected>>', self.dimChanged)
    def getSub(self):
        return self.drawVars['sub'].get()
    def getType(self): 
        return self.drawVars['type'].get()
    def getDim(self):
        return self.drawVars['dim'].get()
    def getProj(self):
        return self.drawVars['proj'].get()
    def getDct(self):
        return {key:self.drawVars[key].get() for key in self.drawVars}
# 子图类型
class DrawTypeSub(DrawType):
    pass
class DarwSystem():
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("数据展示工具")
        self.data = {}
        self.als = []
        self.initConst()
        self.setFrmCtrl()
        frmFig = ttk.Frame(self.root)
        frmFig.pack(side=tk.LEFT,fill=tk.BOTH,expand=tk.YES)
        self.setFrmFig(frmFig)
        self.root.mainloop()
    def initConst(self):
        self.TYPES = ("点线图", "散点图", "条形图")
        self.drawDct = {
            "点线图" : self.drawPlot,
            "散点图" : self.drawScatter,
            "条形图" : self.drawBar
        }
    def setFrmCtrl(self):
        frmCtrl = ttk.Frame(self.root,width=320)
        frmCtrl.pack(side=tk.RIGHT, fill=tk.Y)
        frm = ttk.Frame(frmCtrl, width=320)
        frm.pack(side=tk.TOP, fill=tk.X)
        self.setCtrlButtons(frm)
        self.frmAxis = ttk.Frame(frmCtrl)
        self.frmAxis.pack(side=tk.TOP, fill=tk.X)
        self.addLast(None)
    # ! 工具栏
    def setCtrlButtons(self, frm):
        self.drawTypeDim = DrawType(frm, self.TYPES)
        self.drawTypeDim.pack(side=tk.LEFT)
        ttk.Button(frm, text="📈",width=3,
            command=self.btnDrawImg).pack(side=tk.LEFT)
        ttk.Button(frm, text="📂",width=3,
            command=self.btnLoadData).pack(side=tk.LEFT)
        btn = ttk.Button(frm, text="+", width=3)
        btn.pack(side=tk.LEFT)
        btn.bind("<Button-1>", self.addLast)
        btn = ttk.Button(frm, text="-", width=3)
        btn.pack(side=tk.LEFT)
        btn.bind("<Button-1>", self.deleteLast)
    def addLast(self, evt):
        title = f"坐标{len(self.als)}"
        al = AxisList(self.frmAxis, title, 1, [5,10,30], 
            self.TYPES, self.drawTypeDim.getDct())
        al.pack(side=tk.TOP, fill=tk.X)
        self.als.append(al)
    def deleteLast(self, evt):
        self.als[-1].pack_forget()
        del self.als[-1]
    def btnLoadData(self):
        name = askopenfilename()
        data = np.genfromtxt(name)
        for i, flag in enumerate('xyz'):
            if i >= data.shape[1]:
                return
            self.AL.setOneMode(flag, "外部导入")
            self.data[flag] = self.AL.setData(flag, data[:,i])
    def readDatas(self, al):
        dct = {}
        data = {}
        for flag in self.drawTypeDim.getDim():
            data[flag] = al.setData(flag, **dct)
            dct[flag] = data[flag]
        return data
    def setDrawAxis(self, al):
        sub = int(al.getSub())
        print(sub)
        if sub in self.axDct:
            return self.axDct[sub]
        p = al.getProj() 
        if p == "None":
            ax = self.fig.add_subplot(sub)
        else:
            ax = self.fig.add_subplot(sub, projection=p)
        return ax
    def btnDrawImg(self):
        self.fig.clf()
        keys = self.drawTypeDim.getDim()
        self.axDct = {}
        for al in self.als:
            ax = self.setDrawAxis(al)
            data = self.readDatas(al)
            draw = self.drawDct[al.getDrawType()]
            draw(ax, data, keys)
        self.fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.08)
        self.canvas.draw()
    def drawBar(self, ax, data, keys):
        ax.bar(data['x'], data['y'])
    def drawPlot(self, ax, data, keys):
        ax.plot(*[data[key] for key in keys])
    def drawScatter(self, ax, data, keys):
        ax.scatter(*[data[key] for key in keys])
    def setFrmFig(self, frmFig):
        self.fig = Figure()
        self.canvas = FigureCanvasTkAgg(self.fig,frmFig)
        self.canvas.get_tk_widget().pack(
            side=tk.TOP,fill=tk.BOTH,expand=tk.YES)
        self.toolbar = NavigationToolbar2Tk(self.canvas,frmFig,
            pack_toolbar=False)
        self.toolbar.update()
        self.toolbar.pack(side=tk.RIGHT)
if __name__ == "__main__":
    test = DarwSystem()

以上就是Python实现多子图绘制系统的示例详解的详细内容,更多关于Python多子图绘制系统的资料请关注脚本之家其它相关文章!

相关文章

最新评论