Python绘图之自定义图类型控件实现混合类型图表
Python绘图系统:
基础:将matplotlib嵌入到tkinter|简单的绘图系统|数据导入|三维绘图系统
自定义控件:坐标设置控件|坐标列表控件|支持多组数据的绘图系统
图表类型和风格:散点图和条形图
绘图类型控件
很多时候我们都有在一张图上绘制多种图标的需求,比如数据拟合的时候,用散点图表示原始数据,用曲线图来表示绘图后的结果。从这个角度来说,每一组绘图数据都应该有其自身的绘图类别。换言之,我们在DrawSystem中建立的绘图类型选择框,也需要在AxisFrame中使用。
为了降低代码重复,最好还是新建一个控件,专门用于约定绘图类型。而且更加广泛地讲,除了散点图条形图这种,是二维还是三维,也可算在绘图类型里面。所以,这个绘图类型控件,至少包含两个ComboBox,这对于已经创建过AxisFrame和AxisList的我们来说,属于小儿科水平
class DrawType(ttk.Frame): # ws为两个combobox的宽 def __init__(self, master, types, slctType, slctDim="3", ws=None, **options): super().__init__(master, **options) self.pack() self.types = types # 绘图类型 self.dims = ("1", "2", "3", "1+1", "2+1", "3+1") # 绘图维度 self.initVar(slctType, slctDim) self.initWidgets(ws) def initVar(self, slctType, slctDim): self.drawType = tk.StringVar() self.drawType.set(slctType) self.drawDim = tk.StringVar() if type(slctDim) != str: slctDim = self.dims[int(slctDim)] self.drawDim.set(slctDim) def initWidgets(self, ws): if ws==None: ws = [8, 3] vs = [self.drawType, self.drawDim] slcts = [self.types, self.dims] for i in range(2): slct = ttk.Combobox(self, width=ws[i], textvariable=vs[i]) slct['value'] = slcts[i] slct.pack(side=tk.LEFT) def getType(self): return self.drawType.get() def getDim(self): dim = self.drawDim.get() dimDct = {"1" : "x", "2" : "xy", "3" : "xyz", "1+1": "tx", "2+1": "txy", "3+1": "txyz"} return dimDct[dim]
然后更改DrawSystem,主要是把setCtrlButtons(self, frm)函数的前两句改为
def setCtrlButtons(self, frm): self.drawTypeDim = DrawType(frm, self.TYPES, "点线图") self.drawTypeDim.pack(side=tk.LEFT) # ...
另一方面,两个ComboBox太大了,为了美观,把新增和删除两个按钮上的文字改为加号和减号。修改过后的UI如下
改造AxisList
首先,在AxisList的初始化代码中添加初始化绘图类型的参数
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)
由于更改是输入参数的个数,所以在DrawSystem中调用时,需要把types和slctType这两个参数补上。
然后在initFeature中添加drawTypeDim,
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) frm = ttk.Frame(self._c) frm.pack(pady=2, side=tk.TOP, fill=tk.X) self.drawTypeDim = DrawType(frm, types, slctType) 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)
更改绘图逻辑
最后,更改绘图逻辑。首先,考虑到drawDct的特点,将其改为全局变量。
self.drawDct = { "点线图" : self.drawPlot, "散点图" : self.drawScatter, "条形图" : self.drawBar }
然后,考虑到每次绘图都需要读取AxisList中的绘图类型,从而需要分次调用绘图函数,所以创建窗口这一步也交给btnDrawImg函数,从而绘图函数就只剩下了完完全全的绘图功能。相关代码如下
def btnDrawImg(self): self.fig.clf() keys = self.drawTypeDim.getDim() p = '3d' if 'z' in keys else None ax = self.fig.add_subplot(projection=p) 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])
最后运行结果如下,分别绘制的散点图和曲线图。
源代码
最后附上源代码,写在.py文件里,然后python xx.py就可以正常运行。
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) frm = ttk.Frame(self._c) frm.pack(pady=2, side=tk.TOP, fill=tk.X) self.drawTypeDim = DrawType(frm, types, slctType) self.drawTypeDim.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 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) 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 DrawType(ttk.Frame): # ws为两个combobox的宽 def __init__(self, master, types, slctType, slctDim="3", ws=None, **options): super().__init__(master, **options) self.pack() self.types = types # 绘图类型 self.dims = ("1", "2", "3", "1+1", "2+1", "3+1") # 绘图维度 self.initVar(slctType, slctDim) self.initWidgets(ws) def initVar(self, slctType, slctDim): self.drawType = tk.StringVar() self.drawType.set(slctType) self.drawDim = tk.StringVar() if type(slctDim) != str: slctDim = self.dims[int(slctDim)] self.drawDim.set(slctDim) def initWidgets(self, ws): if ws==None: ws = [8, 3] vs = [self.drawType, self.drawDim] slcts = [self.types, self.dims] for i in range(2): slct = ttk.Combobox(self, width=ws[i], textvariable=vs[i]) slct['value'] = slcts[i] slct.pack(side=tk.LEFT) def getType(self): return self.drawType.get() def getDim(self): dim = self.drawDim.get() dimDct = {"1" : "x", "2" : "xy", "3" : "xyz", "1+1": "tx", "2+1": "txy", "3+1": "txyz"} return dimDct[dim] 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 = ("点线图", "散点图", "条形图") 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=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=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 'xyz': data[flag] = al.setData(flag, **dct) dct[flag] = data[flag] return data def btnDrawImg(self): drawDct = { "点线图" : self.drawPlot, "散点图" : self.drawScatter, "条形图" : self.drawBar } self.fig.clf() keys = self.drawTypeDim.getDim() p = '3d' if 'z' in keys else None ax = self.fig.add_subplot(projection=p) for al in self.als: data = self.readDatas(al) draw = 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混合类型图表的资料请关注脚本之家其它相关文章!
相关文章
Python使用pyautocad+openpyxl处理cad文件示例
这篇文章主要介绍了Python使用pyautocad+openpyxl处理cad文件,结合实例形式分析了Python使用pyautocad与openpyxl模块读写cad文件相关应用操作技巧,需要的朋友可以参考下2019-07-07python中lxml.etree 和 ElementTree 的区别解析
lxml.etree 提供了更多的功能,例如 XPath、XSLT、Relax NG、 和 XML 模式支持,etree 对 Python unicode 字符串的想法与 ElementTree 不同,本文给大家介绍python中lxml.etree 和 ElementTree 的区别,感兴趣的朋友一起看看吧2024-01-01
最新评论