文章目录
- 新增散点图绘制
- 绑定与回调
- 极坐标功能
- 子图绘制功能
- 源代码
- 📈一 三维绘图系统
- 📈二 多图绘制系统
新增散点图绘制
同一坐标系中绘制多个图像是很常见的需求,比如数据拟合的时候,用散点图表示原始数据,用曲线图来表示拟合结果。而这两组数据分别有其自身的绘图类别。
为了降低代码重复,最好还是新建一个控件,专门用于约定绘图类型。而且更加广泛地讲,除了散点图条形图这种,是二维还是三维,也可算在绘图类型里面。所以,这个绘图类型控件,至少包含两个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 = ("x", "xy", "xyz", "tx", "txy", "txyz") # 绘图维度
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):
return self.drawDim.get()
然后更改DrawSystem,主要是把setCtrlButtons(self, frm)函数的前两句改为
def setCtrlButtons(self, frm):
self.drawTypeDim = DrawType(frm, self.TYPES, "点线图")
self.drawTypeDim.pack(side=tk.LEFT)
# ...
另一方面,两个ComboBox太大了,为了美观,把新增和删除两个按钮上的文字改为加号和减号。修改过后的UI如下
首先,在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)
self.drawTypeDim = DrawType(frm, types, slctType)
self.vis = {L : True for L in 'txyz'}
for flag in 'txyz':
btn = ttk.Button(frm, text=flag, wid th=3)
btn.pack(side=tk.LEFT)
btn.bind("<Button-1>", self.btnAxisCollapse)
最后,更改绘图逻辑。简单起见,这里只挑选最经典的三种图像,即点线图、散点图和条形图。首先,创建一个全局变量字典,用于存放这些图像的名称及其对应的绘图函数
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])
最后运行结果如下,分别绘制的散点图和曲线图。
绑定与回调
DrawType类可以设置绘图维度,而绘图维度其实就是坐标轴的个数。所以,一个比较合理的交互逻辑是,改选DrawType的维度后,坐标轴个数也该随之变化。为了实现这个功能,需要为ComboBox绑定一个事件,改动起来非常简单,只需在initWidgets最后加上一行就可以。
def initWidgets(self, ws):
if ws==None: ws = [8, 3]
slct = ttk.Combobox(self, width=ws[0], textvariable=self.drawType)
slct['value'] = self.types
slct.pack(side=tk.LEFT)
slct = ttk.Combobox(self, width=ws[1], textvariable=self.drawDim)
slct['value'] = self.dims
slct.pack(side=tk.LEFT)
slct.bind('<<ComboboxSelected>>', self.dimChanged)
接下来比较重要的则是self.dimChanged的定义。我们希望当Combobox改变时,是另一个控件的内容发生变化,所以self.dimChanged最好是其他控件传入的一个函数。故而需要更改DrawType的初始化函数,即添加一个func参数,然后把这个参数赋给self.dimChanged方法。
def __init__(self, master, types, slctType,
slctDim="xyz", ws=None, func=None, **options):
super().__init__(master, **options)
#。。。
self.dimChanged = func
# 。。。
最后,修改AxisList中初始化DrawType的语句
self.drawTypeDim = DrawType(frm, types, slctType, func=self.dimChanged)
并创建self.dimChanged函数,代码如下,逻辑是根据当前选择的维度来更新txyz这几个AxisFrame。
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 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()
既然可以通过DrawType的回调函数来设置坐标轴,那么单个的x,y,z,t按钮旧没必要存在了。可以将AxisList中的相关代码全都删掉。
极坐标功能
用坐标个数来判断是否绘制三维图的确很直观,但从matplotlib的绘图逻辑来说却非如此,对于matplotlib来说,只有直角坐标是真实的,其他坐标都是数据在直角坐标上的投影罢了,这也是projection这个参数的来源。
所以,DrawType还有进一步升级的空间。即除了图表类型、参数个数之外,还可以加一个投影类型,即用于规范Projection参数。
投影和维度从设计方式来说是完全一致的,只需添加
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():
这样就可以绘制极坐标图了
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8mNrRIlP-1692706688280)(python/plt_tk_16.png)]
子图绘制功能
之前在添加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函数,并且补上之前未添加的getProj函数
def getSub(self):
return self.drawTypeDim.getSub()
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的对象。
在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())
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()