python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python三维绘图

Python实现多组数据三维绘图系统

作者:微小冷

这篇文章主要为大家详细介绍了如何利用Python实现多组数据三维绘图系统,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以了解下

Python绘图系统:

基础:将matplotlib嵌入到tkinter|简单的绘图系统|数据导入|三维绘图系统

自定义控件:坐标设置控件|坐标列表控件

增添和删除坐标数据

在实现坐标列表控件之后,自然要在在绘图系统中创建多组坐标列表,同时需要提供新增或删除对应绘图数据的功能。那么首先得添加两个功能按钮

def setCtrlButtons(self, frm):
    ttk.Button(frm, text="绘图",width=5,
        command=self.btnDrawImg).pack(side=tk.LEFT)
    ttk.Button(frm, text="加载",width=5,
        command=self.btnLoadData).pack(side=tk.LEFT)
    btn = ttk.Button(frm, text="新增", width=5)
    btn.pack(side=tk.LEFT)
    btn.bind("<Button-1>", self.addLast)
    btn = ttk.Button(frm, text="删除", width=5)
    btn.pack(side=tk.LEFT)
    btn.bind("<Button-1>", self.deleteLast)

两个函数,addAxisList在最后面新增一个AxisList,deleteLast则删除最后一个AxisList。这两个功能十分简单,唯一需要注意的就是,在删除AxisList之前,需要取消pack

def addLast(self, evt):
    title = f"坐标{len(self.als)}"
    al = AxisList(self.frmAxis, title, 1, [5,10,20])
    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]

其中涉及到两个全局变量,一个是self.als,用于存放所有的AxisList;另一个是self.frmAxis,是所有AxisList的父组件。

前者可以放在DrawSystem的初始化函数中,

self.als = []

后者则需要更改setFrmCtrl函数

def setFrmCtrl(self, frmCtrl):
    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)

效果如下

更改绘图逻辑

现在有了多组数据,那么相应地绘图逻辑也需要跟着改变。另一方面,原有的全局变量self.data似乎已经很难描述全部数据,所以取消使用全局变量,同时修改绘图最终的绘图函数

def drawPlot(self, ds):
    keys = 'xyz' if 'z' in ds[0] else 'xy'
    p = '3d' if 'z' in ds[0] else None
    ax = self.fig.add_subplot(projection='3d')
    for data in ds:
        ax.plot(*[data[key] for key in keys])

这里把之前的drawPlot和drawPlot3d合并到一起了,并且只是根据第一组坐标数据来判断是否启用3D,这种写法当然十分危险。考虑到日后肯定会通过类似ComboBox来整改,所以这里暂且先这么放着。

而点击绘图按钮之后的响应函数则修改为

def readDatas(self, al):
    dct = {}
    data = {}
    for flag in 'xyz':
        data[flag] = al.setData(flag, **dct)
        dct[flag] = data[flag]
    return data
def btnDrawImg(self):
    self.fig.clf()
    ds = [self.readDatas(al) for al in self.als]
    self.drawPlot(ds)
    self.fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.08)
    self.canvas.draw()

基本逻辑是,遍历所有AxisList并提取数据,然后将所有数据传递给绘图函数进行图像绘制。

效果如下

源代码

最后把源代码附在下面,总计大约不到200行,你就能拥有一个支持多组数据的三维绘图系统了。

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, **options):
        super().__init__(master, **options)
        self.pack()
        self.afs = {}
        self.data = {}
        self.initWidgets(title, widths)
        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()
        self.initFeature()
    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)
    def initFeature(self):
        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.vis = {L : True for L in 'txyz'}
        for flag in 'txyz':
            btn = ttk.Button(frm, text=flag, width=3)
            btn.pack(side=tk.LEFT)
            btn.bind("<Button-1>", self.btnAxisCollapse)
    def btnAxisCollapse(self, evt):
        flag = evt.widget['text']
        self.vis[flag] = not self.vis[flag]
        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 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)
class DarwSystem():
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("数据展示工具")
        self.data = {}
        self.als = []
        frmCtrl = ttk.Frame(self.root,width=320)
        frmCtrl.pack(side=tk.RIGHT, fill=tk.Y)
        self.setFrmCtrl(frmCtrl)
        frmFig = ttk.Frame(self.root)
        frmFig.pack(side=tk.LEFT,fill=tk.BOTH,expand=tk.YES)
        self.setFrmFig(frmFig)
        self.root.mainloop()
    def setFrmCtrl(self, frmCtrl):
        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 addLast(self, evt):
        title = f"坐标{len(self.als)}"
        al = AxisList(self.frmAxis, title, 1, [5,10,20])
        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 setCtrlButtons(self, frm):
        ttk.Button(frm, text="绘图",width=5,
            command=self.btnDrawImg).pack(side=tk.LEFT)
        ttk.Button(frm, text="加载",width=5,
            command=self.btnLoadData).pack(side=tk.LEFT)
        btn = ttk.Button(frm, text="新增", width=5)
        btn.pack(side=tk.LEFT)
        btn.bind("<Button-1>", self.addLast)
        btn = ttk.Button(frm, text="删除", width=5)
        btn.pack(side=tk.LEFT)
        btn.bind("<Button-1>", self.deleteLast)
    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 'xyz':
            data[flag] = al.setData(flag, **dct)
            dct[flag] = data[flag]
        return data
    def btnDrawImg(self):
        self.fig.clf()
        ds = [self.readDatas(al) for al in self.als]
        self.drawPlot(ds)
        self.fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.08)
        self.canvas.draw()
    def drawPlot(self, ds):
        keys = 'xyz' if 'z' in ds[0] else 'xy'
        p = '3d' if 'z' in ds[0] else None
        ax = self.fig.add_subplot(projection='3d')
        for data in ds:
            ax.plot(*[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三维绘图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文