Python绘图系统:
matplotlib中提供了超多种类的图表类型,基于此做一个绘图系统,如果只能画Plot那就太无聊了,接下来就丰富一些图表类型。
为了实现这个功能,先添加一个ComboBox,以供选择相应的绘图方法。这个功能在AxisFrame中已经用到过了,首先需要初始化关联Combobox的StringVar
def initDrawType(self):
self.TYPES = ("点线图", "散点图", "条形图")
self.drawType = tk.StringVar()
self.drawType.set("点线图")
然后在初始化代码中添加self.initDrawType,以及在setCtrlButtons函数中添加combobox组件,
def setCtrlButtons(self, frm):
slct = ttk.Combobox(frm, width=10,
textvariable=self.drawType)
slct['value'] = self.TYPES
slct.pack(side=tk.LEFT)
# 后面是设置画图按钮的
设置完成后结果如下
点线图,就是常见的plot,咱们一直画的就是这个。但现在有了图表类型选择工具,所以其调用逻辑还是要更改一下,其实只是添加一个用于判断的函数就可以了。
def btnDrawImg(self):
drawDct = {
"点线图" : self.drawPlot,
"散点图" : self.drawScatter,
"条形图" : self.drawBar
}
draw = drawDct[self.drawType.get()]
self.fig.clf()
ds = [self.readDatas(al) for al in self.als]
draw(ds)
self.fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.08)
self.canvas.draw()
def drawScatter(self, ds):
pass
def drawBar(self, ds):
pass
其中drawDct是一个函数字典,draw则根据绘图类型选择绘图函数,后面的代码和之前没有区别,这就是函数式语言在效率上的优势。
接下来看看散点图scatter和条形图bar。
scatter的绘图逻辑与plot如出一辙,都是需要x坐标和y坐标
def drawScatter(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.scatter(*[data[key] for key in keys])
效果如下
考虑到三维条形图绘制上比较复杂,所以这里先演示一下二维条形图。
def drawBar(self, ds):
ax = self.fig.add_subplot()
data = ds[0]
ax.bar(data['x'], data['y'])
效果如下
下面是整个工程的源代码,大约200行左右。本篇博客是Python绘图系统的第8篇,争取短期内尽量维持一个比较少的代码行数,以便附在文末。
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("" , 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 = []
self.initDrawType()
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 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 initDrawType(self):
self.TYPES = ("点线图", "散点图", "条形图")
self.drawType = tk.StringVar()
self.drawType.set("点线图")
# ! 工具栏
def setCtrlButtons(self, frm):
slct = ttk.Combobox(frm, width=10,
textvariable=self.drawType)
slct['value'] = self.TYPES
slct.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=5)
btn.pack(side=tk.LEFT)
btn.bind("" , self.addLast)
btn = ttk.Button(frm, text="删除", width=5)
btn.pack(side=tk.LEFT)
btn.bind("" , self.deleteLast)
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 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
}
draw = drawDct[self.drawType.get()]
self.fig.clf()
ds = [self.readDatas(al) for al in self.als]
draw(ds)
self.fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.08)
self.canvas.draw()
def drawScatter(self, ds):
pass
def drawBar(self, ds):
ax = self.fig.add_subplot()
data = ds[0]
ax.bar(data['x'], data['y'])
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 drawScatter(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.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()
```