当前的图表和子图可以使用plt.gcf()和plt.gca()获得,分别表示Get Current Figure和Get Current Axes。在pyplot模块中,许多函数都是对当前的Figure或Axes对象进行处理,比如说:plt.plot()实际上会通过plt.gca()获得当前的Axes对象ax,然后再调用ax.plot()方法实现真正的绘图。

import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *root = Tk()
root.title("tkinter and matplotlib")f = Figure(figsize=(5, 4), dpi=100)
f_plot = f.add_subplot(111)def other_picture_alg(): #数据相关的算法应该与plot分离开x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]y = [3, 6, 9, 12, 15, 18, 15, 12, 15, 18]return x, ydef draw_picture():f_plot.clear()x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #关于数据的部分可以提取出来y = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]f_plot.plot(x, y)canvs.draw()def draw_picture2():f_plot.clear()x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #关于数据的部分可以提取出来y = [2, 4, 6, 8, 10, 8, 6, 4, 2, 0]f_plot.plot(x, y)canvs.draw()def draw_picture3():f_plot.clear()x, y = other_picture_alg() # 使用由算法生成的数据,可以避免重复的运算过程f_plot.plot(x, y)canvs.draw()canvs = FigureCanvasTkAgg(f, root)
canvs.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
Button(root, text='pic', command=draw_picture).pack()
Button(root, text='pic2', command=draw_picture2).pack()
Button(root, text='pic3', command=draw_picture3).pack()root.mainloop()

matplotlib与tkinter 结合

import tkinter as tk
import matplotlib
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure# matplotlib.use('TkAgg')root = tk.Tk()
root.title("matplotlib in tkinter")# set a figure
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
a.plot(t, s)canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()def on_key_event(event):print('you press %s' %event.key)key_press_handler(event, canvas, toolbar)canvas.mpl_connect('key_press_event', on_key_event)def _quit():root.quit()root.destroy()button = tk.Button(root, text='quit', command=_quit)
button.pack(side=tk.BOTTOM)root.mainloop()

结合后加图像操作按钮

有些场合,我们需要对数据可视化。单是靠 tkinter 难度太大,而且做出来的效果不一定理想。此时,将 tkinter 与 matplotlib 结合,是最好的选择。知识点:将 tkinter 与 matplotlib 结合的整个套路是固定的,只需要关心我们的绘图逻辑和程序逻辑即可。

import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import tkinter as tk
class Application(tk.Tk):'''文件夹选择程序界面与逻辑分离'''def __init__(self):'''初始化'''super().__init__() # 有点相当于tk.Tk()self.wm_title("Embed matplotlib in tkinter")self.createWidgets()def createWidgets(self):'''界面'''fig = Figure(figsize=(5, 4), dpi=100)self.ax = fig.add_subplot(111)self.canvas = FigureCanvasTkAgg(fig, master=self)self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)toolbar = NavigationToolbar2TkAgg(self.canvas, self)toolbar.update()footframe = tk.Frame(master=self).pack(side=tk.BOTTOM)tk.Button(master=footframe, text='重画', command=self.draw).pack(side=tk.BOTTOM)tk.Button(master=footframe, text='退出', command=self._quit).pack(side=tk.BOTTOM)self.draw() # 绘图def draw(self):'''绘图逻辑'''x = np.random.randint(0, 50, size=100)y = np.random.randint(0, 50, size=100)# self.fig.clf() # 方式一:①清除整个Figure区域# self.ax = self.fig.add_subplot(111) # ②重新分配Axes区域self.ax.clear() # 方式二:①清除原来的Axes区域self.ax.scatter(x, y, s=3) # 重新画self.canvas.show()def _quit(self):'''退出'''self.quit() # 停止 mainloopself.destroy() # 销毁所有部件
if __name__ == '__main__':# 实例化Applicationapp = Application()# 主消息循环:app.mainloop()

结果:

1.title设置图像标题
(1)title常用参数
fontsize设置字体大小,默认12,可选参数 ['xx-small', 'x-small', 'small', 'medium', 'large','x-large', 'xx-large']
fontweight设置字体粗细,可选参数 ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
fontstyle设置字体类型,可选参数[ 'normal' | 'italic' | 'oblique' ],italic斜体,oblique倾斜
verticalalignment设置水平对齐方式 ,可选参数 : 'center' , 'top' , 'bottom' ,'baseline' 
horizontalalignment设置垂直对齐方式,可选参数:left,right,center
rotation(旋转角度)可选参数为:vertical,horizontal 也可以为数字
alpha透明度,参数值0至1之间
backgroundcolor标题背景颜色
bbox给标题增加外框 ,常用参数如下:
boxstyle方框外形
facecolor(简写fc)背景颜色
edgecolor(简写ec)边框线条颜色
edgewidth边框线条大小

(2)title例子:

plt.title('Interesting Graph',fontsize='large',fontweight='bold') 设置字体大小与格式
plt.title('Interesting Graph',color='blue') 设置字体颜色
plt.title('Interesting Graph',loc ='left') 设置字体位置
plt.title('Interesting Graph',verticalalignment='bottom') 设置垂直对齐方式
plt.title('Interesting Graph',rotation=45) 设置字体旋转角度
plt.title('Interesting',bbox=dict(facecolor='g', edgecolor='blue', alpha=0.65 )) 标题边框

面向对象api例子:

import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[3,6,7,9,2]
 
fig,ax=plt.subplots(1,1)
ax.plot(x,y,label='trend')
ax.set_title('title test',fontsize=12,color='r')
plt.show()
2.annotate标注文字
(1)annotate语法说明 :annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,..)

s 为注释文本内容 
xy 为被注释的坐标点
xytext 为注释文字的坐标位置
xycoords 参数如下:

figure points          points from the lower left of the figure 点在图左下方
figure pixels          pixels from the lower left of the figure 图左下角的像素
figure fraction       fraction of figure from lower left 左下角数字部分
axes points           points from lower left corner of axes 从左下角点的坐标
axes pixels           pixels from lower left corner of axes 从左下角的像素坐标
axes fraction        fraction of axes from lower left 左下角部分
data                     use the coordinate system of the object being annotated(default) 使用的坐标系统被注释的对象(默认)
polar(theta,r)       if not native ‘data’ coordinates t
extcoords 设置注释文字偏移量

| 参数 | 坐标系 | 
         | 'figure points' | 距离图形左下角的点数量 | 
         | 'figure pixels' | 距离图形左下角的像素数量 | 
         | 'figure fraction' | 0,0 是图形左下角,1,1 是右上角 | 
         | 'axes points' | 距离轴域左下角的点数量 | 
         | 'axes pixels' | 距离轴域左下角的像素数量 | 
         | 'axes fraction' | 0,0 是轴域左下角,1,1 是右上角 | 
         | 'data' | 使用轴域数据坐标系 |

arrowprops  #箭头参数,参数类型为字典dict

width           the width of the arrow in points                              点箭头的宽度
headwidth   the width of the base of the arrow head in points  在点的箭头底座的宽度
headlength  the length of the arrow head in points                   点箭头的长度
shrink          fraction of total length to ‘shrink’ from both ends  总长度为分数“缩水”从两端
facecolor     箭头颜色
bbox给标题增加外框 ,常用参数如下:

boxstyle方框外形
  facecolor(简写fc)背景颜色
  edgecolor(简写ec)边框线条颜色
  edgewidth边框线条大小
 bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5)  #fc为facecolor,ec为edgecolor,lw为lineweight

(2)案例

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 6)
y = x * x
plt.plot(x, y, marker='o')
for xy in zip(x, y):
    plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points')
plt.show()

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05))

3.text设置文字说明
(1)text语法说明

text(x,y,string,fontsize=15,verticalalignment="top",horizontalalignment="right")

x,y:表示坐标值上的值
string:表示说明文字
fontsize:表示字体大小
verticalalignment:垂直对齐方式 ,参数:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
horizontalalignment:水平对齐方式 ,参数:[ ‘center’ | ‘right’ | ‘left’ ]
xycoords选择指定的坐标轴系统:

figure points          points from the lower left of the figure 点在图左下方
figure pixels          pixels from the lower left of the figure 图左下角的像素
figure fraction       fraction of figure from lower left 左下角数字部分
axes points           points from lower left corner of axes 从左下角点的坐标
axes pixels           pixels from lower left corner of axes 从左下角的像素坐标
axes fraction        fraction of axes from lower left 左下角部分
data                     use the coordinate system of the object being annotated(default) 使用的坐标系统被注释的对象(默认)
polar(theta,r)       if not native ‘data’ coordinates t
arrowprops  #箭头参数,参数类型为字典dict

width           the width of the arrow in points                              点箭头的宽度
headwidth   the width of the base of the arrow head in points  在点的箭头底座的宽度
headlength  the length of the arrow head in points                   点箭头的长度
shrink          fraction of total length to ‘shrink’ from both ends  总长度为分数“缩水”从两端
facecolor     箭头颜色
bbox给标题增加外框 ,常用参数如下:

boxstyle方框外形
  facecolor(简写fc)背景颜色
  edgecolor(简写ec)边框线条颜色
  edgewidth边框线条大小
 bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5)  #fc为facecolor,ec为edgecolor,lw为lineweight

(2)案例

文字格式与位置:

import matplotlib.pyplot as plt
fig = plt.figure()
plt.axis([0, 10, 0, 10])
t = "This is a really long string that I'd rather have wrapped so that it"\
    " doesn't go outside of the figure, but if it's long enough it will go"\
    " off the top or bottom!"
plt.text(4, 1, t, ha='left', rotation=15, wrap=True)
plt.text(6, 5, t, ha='left', rotation=15, wrap=True)
plt.text(5, 5, t, ha='right', rotation=-15, wrap=True)
plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',va='top',wrap=True)
plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)
plt.text(-1, 0, t, ha='left', rotation=-15, wrap=True)
plt.show()

花式文本框:
import matplotlib.pyplot as plt
plt.text(0.6, 0.5, "test", size=50, rotation=30.,ha="center", va="center",bbox=dict(boxstyle="round",ec=(1., 0.5, 0.5),fc=(1., 0.8, 0.8),))
plt.text(0.5, 0.4, "test", size=50, rotation=-30.,ha="right", va="top",bbox=dict(boxstyle="square",ec=(1., 0.5, 0.5),fc=(1., 0.8, 0.8),))
plt.draw()
plt.show()

数学公式:

plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',fontsize=20)

--------------------- 
作者:开码牛 
来源:CSDN 
原文:https://blog.csdn.net/helunqu2017/article/details/78659490 
版权声明:本文为博主原创文章,转载请附上博文链接!

Python matplotlib与tkinter结合相关推荐

  1. Python+matplotlib绘制函数曲线查找函数极值

    推荐图书: <Python程序设计基础(第2版)>,ISBN:9787302490562,董付国,清华大学出版社,第16次印刷,清华大学出版社2019年度畅销图书 图书详情: 配套资源:用 ...

  2. Python Matplotlib教程

    Python Matplotlib教程 文章目录 Python Matplotlib教程 教程特点 阅读条件 数据可视化是什么 数据可视化 数据可视化应用场景 Matplotlib是什么 Matplo ...

  3. Python+matplotlib可视化自定义轴域大小和位置

    推荐图书: <Python可以这样学>,ISBN:9787302456469,董付国,清华大学出版社,第9次印刷 图书详情(京东): 董付国老师17本Python系列图书均提供配套教学资源 ...

  4. Python matplotlib可视化:用Matplotlib的bar_label函数为条形图添加数值标记(在每一个条形的外侧顶部)

    Python matplotlib可视化:用Matplotlib的bar_label函数为条形图添加数值标记(在每一个条形的外侧顶部) 目录

  5. Python matplotlib可视化:在Matplotlib中为坐标轴刻度添加自定义符号(例如,货币符号¥$等)、水平条形图(horizontal bar)

    Python matplotlib可视化:在Matplotlib中为坐标轴刻度添加自定义符号(例如,货币符号¥$等).水平条形图(horizontal bar) 目录

  6. Python matplotlib可视化:自定义轴标签格式化函数(在轴刻度上添加自定义的数值以及符号形式)、使用自定义函数在Matplotlib中为坐标轴刻度添加自定义符号(例如,货币符号¥$等)

    Python matplotlib可视化:自定义轴标签格式化函数(在轴刻度上添加自定义的数值以及符号形式).使用自定义函数在Matplotlib中为坐标轴刻度添加自定义符号(例如,货币符号¥$等) 目 ...

  7. Python matplotlib可视化:用Matplotlib的bar_label函数自定义条形图的数值标签、用Matplotlib的bar_label函数为条形图添加数值标记(在每一个条形的中部)

    Python matplotlib可视化:用Matplotlib的bar_label函数自定义条形图的数值标签.用Matplotlib的bar_label函数为条形图添加数值标记(在每一个条形的中部) ...

  8. python matplotlib 简单用法

    python matplotlib 简单用法 具体内容请参考官网 代码 import matplotlib.pyplot as plt import numpy as np # 支持中文 plt.rc ...

  9. 老咸鱼今天告诉你用Python matplotlib 各种图绘制流线图,难怪老板放纵他

    复习回顾 在Python关于绘图,Mlab提供开源的matplotlib模块,不仅可以绘制折线图.柱状图.散点图等常规图外,还支持绘制量场图.频谱图.提琴图.箱型图等特殊图,例举往期文章可前往查看详情 ...

最新文章

  1. java解析五元组_pcap文件解析,并且按照五元组分类
  2. 高逼格UILabel的闪烁动画效果
  3. Linux编程简介——动态链接库
  4. DDoS攻击的大量增加给企业带来了新的威胁——Vecloud
  5. DL之AlexNet:利用卷积神经网络类AlexNet实现猫狗分类识别(图片数据增强→保存h5模型)
  6. linux软件包管理 pdf,vSphere Storage Appliance 安装和管理 PDF
  7. 最大似然估计、MAP、贝叶斯估计
  8. POJ 3237 Tree (树链拆分)
  9. M1 Mac 档案的临时暂存区工具: Yoink
  10. UML常用图--类图,用例图,序列图(时序图),协作图(通信图),状态图,活动图
  11. HAL库 STM32 串口通信函数
  12. (2020年下半年软件设计师49题)程序设计语言的大多数语法现象可以用CFG(上下文无关文法)表示。下面的CFG产生式集用于描述简单算术表达式,其中+ - * 表示加、减、乘运算,id表示单个字母表示
  13. python3数据库框架_python3大框架简介 小收藏
  14. java遍历变量_java – 循环遍历众多变量
  15. 无线智能蓝牙追踪防丢器
  16. 微信小程序分享生成海报(自带二维码)+头像+昵称
  17. 常用测试工具和框架归类
  18. 基于python的个人博客系统的设计开题报告_基于JavaSSM框架的个人博客系统设计与实现开题报告...
  19. 用地预审与选址意见书
  20. 试用python库meteva(气象行业)

热门文章

  1. 老板:为什么你们的软件迟迟上不了线?
  2. Android切换深色模式导致布局字体变小的解决方案
  3. JavaScript基础知识梳理
  4. 新闻文本分类--任务5 基于深度学习的文本分类2
  5. zcurd上了开源中国头条
  6. Java输入一个月份判断春夏秋冬季节中switch与if使用
  7. angular5解决chrome等浏览器不能播放.m3u8视频流
  8. 详述 Java NIO 以及 Socket 处理粘包和断包方法
  9. 有关笔记本电池校正的方法
  10. 洛谷 P1862 输油管道问题