python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python极坐标

Python绘图之实现绘制极坐标图像

作者:微小冷

这篇文章主要介绍了如何利用python绘制极坐标图像,文中的示例代码讲解详细,具有一定的的参考价值,感兴趣的小伙伴可以跟随小编一起学习一下

Python绘图系统:

从0开始实现一个三维绘图系统

自定义控件:坐标设置控件|坐标列表控件|支持多组数据的绘图系统

图表类型和风格:散点图和条形图|混合类型图表

旧代码整改

用坐标个数来判断是否绘制三维图的确很直观,但从matplotlib的绘图逻辑来说却非如此,对于matplotlib来说,只有直角坐标是真实的,其他坐标都是数据在直角坐标上的投影罢了,这也是projection这个参数的来源。

所以,DrawType还有进一步升级的空间。即除了图表类型、参数个数之外,还可以加一个投影类型,即用于规范Projection参数。

但在此之前,需要对其做一点小的整改。即最开创建DrawType这个类的时候,用数字来表示坐标个数。但后来发现,其实这六种组合如果用字母表示会更加方便。所以DrawType初始化函数中的self.dims可做如下修改

self.dims = ("x", "xy", "xyz", "tx", "txy", "txyz")    # 绘图维度

同时getDim函数也不用那么麻烦了,直接像下面这样。

def getDim(self):
    return self.drawDim.get()

同时,DrawType已经指明了坐标轴,那么单个的x,y,z,t按钮旧没必要存在了。可以将AxisList中的相关代码全都删掉。

投影下拉选框

投影和维度从设计方式来说是完全一致的,只需添加

self.projs = ("None", "3d", "polar")

在initVar中添加

self.drawDim = tk.StringVar()
self.drawDim.set(dim)

在initWidgets中添加

slct = ttk.Combobox(self, width=ws[1], textvariable=self.drawProj)
slct['value'] = self.projs
slct.pack(side=tk.LEFT, padx=2)

并创建getProj函数

def getProj(self):
    return self.drawProj.get()

这个时候界面又变得臃肿了,所以再调整调整,最后效果为

绘图逻辑

下面更新绘图逻辑,尽管只是多了一个设定坐标映射的功能,但从可扩展性的角度触发,还是新建一个专门设置坐标轴的函数比较好。故而在DrawSystem中添加setDrawAxis函数

def setDrawAxis(self):
    p = self.drawTypeDim.getProj() 
    if p == "None":
        ax = self.fig.add_subplot()
    else:
        ax = self.fig.add_subplot(projection=p)
    return ax

然后发现了一个小bug,就是无论在绘图时是否使用z轴坐标,但会一并读取z轴数据,这里稍作改善,将readDatas中的循环改为

for flag in self.drawTypeDim.getDim():

这样就可以绘制极坐标图了

源代码

虽然新增了一个功能,但因为优化了声明绘图维度的部分代码,所以代码行数并没有太多改变,所有源代码如下,只需放在.py文件中并用Python调用,就可以愉快地画图了

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, slctType,        # 绘图类型Combobox的参数
        **options):
        super().__init__(master, **options)
        self.pack()
        self.afs = {}
        self.data = {}
        self.initWidgets(title, widths)
        self.initFeature(types, slctType)
        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, slctType):
        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, slctType, 
            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 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)
# 绘图类型和维度
class DrawType(ttk.Frame):
    # ws为两个combobox的宽
    def __init__(self, master, types, slctType, 
        slctDim="xyz", slctProj='3d', ws=None, func=None, **options):
        super().__init__(master, **options)
        self.pack()
        self.types = types  # 绘图类型
        self.dims = ("x", "xy", "xyz", "tx", "txy", "txyz")    # 绘图维度
        self.projs = ("None", "3d", "polar")
        self.dimChanged = func
        self.initVar(slctType, slctDim, slctProj)
        self.initWidgets(ws)
    def initVar(self, slctType, dim, proj):
        self.drawType = tk.StringVar()
        self.drawType.set(slctType)
        self.drawDim = tk.StringVar()
        self.drawDim.set(dim)
        self.drawProj = tk.StringVar()
        self.drawProj.set(proj)
    def initWidgets(self, ws):
        if ws==None: ws = [5, 5, 3]
        slct = ttk.Combobox(self, width=ws[0], textvariable=self.drawType)
        slct['value'] = self.types
        slct.pack(side=tk.LEFT, padx=2)
        slct = ttk.Combobox(self, width=ws[1], textvariable=self.drawProj)
        slct['value'] = self.projs
        slct.pack(side=tk.LEFT, padx=2)
        slct = ttk.Combobox(self, width=ws[2], textvariable=self.drawDim)
        slct['value'] = self.dims
        slct.pack(side=tk.LEFT, padx=2)
        slct.bind('<<ComboboxSelected>>', self.dimChanged)
    def getType(self): 
        return self.drawType.get()
    def getDim(self):
        return self.drawDim.get()
    def getProj(self):
        return self.drawProj.get()
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,20], 
            self.TYPES, self.drawTypeDim.getType())
        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):
        p = self.drawTypeDim.getProj() 
        if p == "None":
            ax = self.fig.add_subplot()
        else:
            ax = self.fig.add_subplot(projection=p)
        return ax
    def btnDrawImg(self):
        self.fig.clf()
        keys = self.drawTypeDim.getDim()
        p = '3d' if 'z' in keys else None
        ax = self.setDrawAxis()
        for al in self.als:
            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极坐标的资料请关注脚本之家其它相关文章!

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