python,在tkinter窗口中用matplotlib的figure对象画图,plot图例,plot文本,plot坐标轴,plot刻度,plot网格,plot水平线

2023-05-16

文章目录

  • 1,创建一个Figure对象
    • 1.1 Figure对象
  • 2,在tkinter窗口中用matplotlib的figure对象画图
    • 2.1,效果展示
    • 2.2,代码

1,创建一个Figure对象

1.1 Figure对象

https://segmentfault.com/a/1190000006158803

  1. 在matplotlib中,整个图像为一个Figure对象。在Figure对象中可以包含一个,或者多个Axes对象。每个Axes对象都是一个拥有自己坐标系统的绘图区域。

2,在tkinter窗口中用matplotlib的figure对象画图

2.1,效果展示

2.2,代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.ticker import MultipleLocator
from matplotlib.figure import Figure
from tkinter import *
# import tkinter as tk
import random
import time


class FigurePlot(object):
    def __init__(self, root, shape):
        self.wnd = root

        fig = Figure()

        plot_frame = Frame(self.wnd, width=shape[0], height=shape[1], bg='green')
        plot_frame.propagate(0)
        plot_frame.pack(side=TOP, fill=BOTH)
        #--------------------------------------------------------------
        self.canvas = FigureCanvasTkAgg(fig, master=plot_frame)
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
        #--------------------------------------------------------------
        self.axis1 = fig.add_subplot(111)
        self.axis1.set_ylim((-10,10))    #set the Y-axis interval
        self.axis1.yaxis.set_minor_locator(MultipleLocator(2))
        self.axis1.yaxis.set_major_locator(MultipleLocator(5))
        self.axis1.tick_params(labelsize=7)
        self.axis1.grid(True, which='minor', axis='y', c='c', linestyle='-.', 
                                                            linewidth=0.2)    #
#         self.axis1.get_yaxis().set_visible(False)    #close the ordinate
        self.axis1.get_xaxis().set_visible(False)    #close the ordinate
        self.axis1.spines['right'].set_visible(False)    #close axes
        self.axis1.xaxis.set_ticks_position('top')
        self.axis1.spines['top'].set_position(('data', 0))    

class CrossLinePlot(object):
    def __init__(self):
        self.start_time = time.time()
        self.count = 0
        self.bar_size = 10
        self.time_interval = 4
        self.p_ab = 0
        self.p_ba = 0
        self.v_ab = 0
        self.v_ba = 0
        self.list_xy = []
        for i in range(self.bar_size):
            data = [i,0,0,0,0,0]
            self.list_xy.insert(0, data) 
        self.index = i

class ShowPlot(object):
    def __init__(self, root):
        self.cross_plot = CrossLinePlot()
        self.wnd = root

    def show_statistics(self, p_value, v_value):
        self.cross_plot.p_ab += p_value[0]
        self.cross_plot.p_ba += p_value[1]
        self.cross_plot.v_ab += v_value[0]
        self.cross_plot.v_ba += v_value[1]

        start_time = self.cross_plot.start_time
        time_interval = self.cross_plot.time_interval
        bar_size = self.cross_plot.bar_size
        bar_width = 0.3
        now_time = time.time()
        if int((now_time-start_time)/time_interval)-self.cross_plot.count >= 1:
            self.cross_plot.count = int((now_time-start_time)/time_interval)
            y1 = self.cross_plot.p_ab
            y2 = -self.cross_plot.p_ba
            y3 = self.cross_plot.v_ab
            y4 = -self.cross_plot.v_ba
            t = int(now_time-start_time)
            self.cross_plot.index += 1
            data = [self.cross_plot.index, t, y1, y2, y3, y4]
            self.cross_plot.list_xy.insert(0, data)
            if len(self.cross_plot.list_xy) > bar_size:
                del self.cross_plot.list_xy[bar_size]
            self.cross_plot.p_ab = 0
            self.cross_plot.p_ba = 0
            self.cross_plot.v_ab = 0
            self.cross_plot.v_ba = 0
            self.wnd.fig_plot.axis1.cla()
        
            a = np.array(self.cross_plot.list_xy)
            a = np.transpose(a)
            a = a.tolist()
            
            self.wnd.fig_plot.axis1.bar(x=a[0], height=a[2], 
                                        color='r', width=bar_width,
                                        label='person in')
            self.wnd.fig_plot.axis1.bar(x=a[0], height=a[3], 
                                        color='g', width=bar_width,
                                        label='person out')
            self.wnd.fig_plot.axis1.bar(x=list(map(lambda n:n+bar_width,a[0])), 
                                        height=a[4], 
                                        color='b', width=bar_width,
                                        label='vehicle in')
            self.wnd.fig_plot.axis1.bar(x=list(map(lambda n:n+bar_width,a[0])), 
                                        height=a[5], 
                                        color='m', width=bar_width,
                                        label='vehicle out')
            #add a legend
            self.wnd.fig_plot.axis1.legend(prop={'size':6},
                                        bbox_to_anchor=(0, 1, 1, 0),
                                        ncol=4, loc=3, mode='expand')
            in_max = 0
            out_max = 0
            in_c = 'c'
            out_c = 'c'
            for x,t,y1,y2,y3,y4 in zip(a[0],a[1],a[2],a[3],a[4],a[5]):
                in_max = y1 if y1>y3 and y1>in_max else(
                                y3 if y3>=y1 and y3>=in_max else in_max) 
                out_max = y2 if y2<y4 and y2<out_max else(
                                y4 if y4<=y2 and y4<=out_max else out_max)
                in_c = 'r' if in_max==y1 else('b' if in_max==y3 else in_c) 
                out_c = 'g' if out_max==y2 else('m' if out_max==y4 else out_c) 
#                 self.wnd.axis1.text(x, y1, y1, ha='left', va='bottom')
#                 self.wnd.axis1.text(x, y2, -y2, ha='left', va='top')
#                 self.wnd.axis1.text(x+bar_width, y1, y3, ha='center', va='bottom')
#                 self.wnd.axis1.text(x+bar_width, -y2, y4, ha='center', va='top')
                self.wnd.fig_plot.axis1.text(x, -12, int(t%60), size=7,
                                                ha='left', va='bottom')

            self.wnd.fig_plot.axis1.text(x+11, in_max, in_max, ha='left', va='center')
            self.wnd.fig_plot.axis1.text(x+11, out_max, -out_max, ha='left', va='center')
            self.wnd.fig_plot.axis1.hlines(in_max, x, x+10, 
                                                color=in_c, linewidth=0.3)
            self.wnd.fig_plot.axis1.hlines(out_max, x, x+10, 
                                                color=out_c, linewidth=0.3)
            self.wnd.fig_plot.axis1.text(-0.1, 0.5, 
                                time.strftime('%Y-%m-%d  %H:%M', time.localtime()), 
                                ha='right', va='center',
                                rotation='vertical',
                                transform=self.wnd.fig_plot.axis1.transAxes)
            self.wnd.fig_plot.axis1.set_ylim((-10,10))    #set the Y-axis interval
#             self.wnd.axis1.spines['right'].set_visible(False)    #close axes
            self.wnd.fig_plot.axis1.xaxis.set_ticks_position('top')
            self.wnd.fig_plot.axis1.spines['top'].set_position(('data', 0))    
            
            #add the grid
            self.wnd.fig_plot.axis1.yaxis.set_minor_locator(MultipleLocator(2))
            self.wnd.fig_plot.axis1.yaxis.set_major_locator(MultipleLocator(5))
            self.wnd.fig_plot.axis1.grid(True, which='minor', axis='y', 
                                                c='c', linestyle='-.',
                                                linewidth=0.2)    
            
            self.wnd.fig_plot.canvas.draw()

class RootWindow(object):
    def __init__(self, shape, locate):
        self.wnd = Tk()
        self.wnd.resizable(width=False,height=False)
        self.wnd.withdraw()
        s_shape = str(shape[0])+'x'+str(shape[1])
        s_locate = '+' + str(locate[0]-shape[0]) + '+' + str(locate[1])
        self.wnd.geometry(s_shape + s_locate)
        self.wnd.title("gigure & tkinter demo")
        
        label_local = (0, 5)
        label = Label(self.wnd, text='number of statistical')
        label.place(x=label_local[0], y=label_local[1])

        fig_frame_shape = (shape[0],shape[1]-40)
        fig_frame_local = (0, 40)
        fig_frame = Frame(self.wnd, width=fig_frame_shape[0], 
                                    height=fig_frame_shape[1])
        fig_frame.propagate(0)
        fig_frame.place(x=fig_frame_local[0], y=fig_frame_local[1])
        self.fig_plot = FigurePlot(fig_frame, fig_frame_shape)

    def wnd_update(self):
        self.wnd.update()
        self.wnd.deiconify()


if __name__ == '__main__':
    root = RootWindow((800,400),(500,300))    
    show_plot = ShowPlot(root)
    while True:
        a1 = random.randint(0, 4)
        time.sleep(0.5)
        a2 = random.randint(0, 4)
        time.sleep(0.5)
        a3 = random.randint(0, 4)
        time.sleep(0.5)
        a4 = random.randint(0, 4)
        time.sleep(0.5)
        show_plot.show_statistics((a1, a2), (a3, a4))
        root.wnd_update()

    root.wnd.mainlop()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python,在tkinter窗口中用matplotlib的figure对象画图,plot图例,plot文本,plot坐标轴,plot刻度,plot网格,plot水平线 的相关文章

  • gstreamer学习(一) gstreamer-rtsp-server环境安装

    gstreamer rtsp server环境安装 Linux环境下 两种方式 xff1a 第一种方式 xff0c 通过官网安装 xff08 如果是Linux环境 xff0c 可以直接通过软件包工具进行安装 xff09 xff0c 点击进入
  • 用C++打开指定网址

    用C 43 43 打开指定网址原理 system 命令 就像这样 xff1a span class token macro property span class token directive hash span span class t
  • 项目遇到的各种异常抛出及解决方法

    项目遇到的各种异常抛出及解决方法 xff1a 1 java lang NumberFormatException xff1a 类型格式异常 第一次遇到的异常抛出原因及解决方法 xff1a 项目运行没有问题 xff0c 各种接口能正常查询出数
  • 【STC8学习笔记】STC8A8K64S4A12精准延时函数设置

    在设置单片机精准的延时函数的时候 xff0c 给大家一个方法 xff0c STC ISP有一个延时函数计算器 xff0c 可以计算出想要的延时 我的例程也是基于这个软件生成的 xff0c 我生成一个1ms和1us出来 xff0c 剩下的我再
  • vc版本与vs版本对应关系

    vc版本与vs版本对应关系 最近在整理之前代码 xff0c 用cmake编译一直报错 xff0c 忘记了opencv3 1 0不支持vs2019 xff0c 所以在这里总结下vc版本与vs版本对应关系 VC版本号 VS对应版本 vc6 VC
  • cmake编译依赖opencv的c++库

    前面一篇主要讲了c 43 43 项目怎么在本地配置opencv过程 xff0c 这种方式缺点就是只能在开发着本地环境编译 xff0c 换台电脑就会出现环境配置问题 接下来主要讲解 xff0c 使用cmake编译 xff0c 生成一个依赖op
  • c++ stl 迭代器iterators(traits编程技法)

    文章目录 1 1 迭代器设计思维 stl关键所在1 2 迭代器是一种smart pointer1 3 迭代器相应型别 xff08 associated types xff09 1 4 traits编程技法 stl源代码门匙1 4 1 val
  • 如何用算法把一个十进制数转为十六进制数-C语言基础

    这一篇文章要探讨的是 如何用算法实现十进制转十六进制 并不涉及什么特别的知识点 属于C语言基础篇 在翻找素材的时候 xff0c 发现一篇以前写的挺有意思的代码 xff0c 这篇代码里面涉及的知识点没有什么好讲的 xff0c 也没有什么特别的
  • 关于 Qt使用QJsonObject解析失败的问题。

    1 问题 在QJsonObject转 toInt toLongLong 等类型时 xff0c 转换失败 但是转toString xff08 xff09 没有任何问题 列如 xff1a 解决方法 xff1a 这样 xff0c 就可以结局问题
  • char 和 string 的相互转换

    一个char字符转为string span class token keyword char span ch span class token operator 61 span span class token char 39 A 39 s
  • C++STL标准库学习总结/索引/学习建议

    前言 xff1a 如果刚刚开始学习STL标准库 xff0c 不知道从哪里入手学习的话 xff0c 建议去中国大学mooc平台 xff0c 先学习北京大学郭炜老师的 程序设计与算法 xff08 一 xff09 C语言程序设计 xff08 ht
  • Python 调用API接口方式,通过http.client调用api接口,远程调用flask接口方式

    一 创建接口 xff08 如果调用别人的接口 xff0c 跳过此条 xff09 如果没有api xff0c 首先自己写一个接口玩一下 xff1a 必备知识 xff1a 一个项目最基本的文件 xff0c 接口run py文件 config文件
  • git tag和branch的区别

    tag 和branch的区别 Git tag是一系列commit的中的一个点 xff0c 只能查看 xff0c 不能移动 branch是一系列串联的commit的线 git tag的用法 我们常常在代码封板时 使用git 创建一个tag 这
  • 结构体对齐计算(超详细讲解,一看就会)

    想要计算结构体大小 xff0c 咱就先要清楚结构体内存对齐的规则 xff1a 1 结构体的第一个成员直接对齐到相对于结构体变量起始位置为0处偏移 2 从第二个成员开始 xff0c 要对齐到某个 对齐数 的整数倍的偏移处 3 结构体的总大小
  • RTK差分编码

    一 概念 DCB xff08 Differential Code Bias 差分码偏差 xff09 是全球卫星导航系统 xff08 GNSS xff09 中 xff0c 通过不同信号得到的观测值之间存在的系统性偏差 DCB是由卫星和接收机硬
  • 详解JAVA的事件监听机制和观察者设计模式

    一 事件监听机制的三要素 事件源 事件监听器 xff0c 事件对象 监听器一般是JAVA接口 xff0c 用来约定可以执行的操作 二 事件监听机制简要说明 事件源注册一个或者多个事件监听器 xff0c 事件源对象状态发生变化或者被操作时 x
  • Nginx控制IP(段)的访问策略配置

    Nginx engine x 是一个高性能的HTTP和反向代理web服务器 xff0c 同时也提供了IMAP POP3 SMTP服务 有着负载均衡 动静分离等强大的功能 xff0c 而且还有众多三方插件来满足应用要求 这里重点介绍nginx
  • 敏捷开发-互联网时代的软件开发方式

    一 什么是敏捷开发 敏捷开发简单的描述为 xff1a 是一种应对需求快速变化的软件开发方式 敏捷开发的核心思想就是小步快跑 不断迭代 xff0c 在一次次的迭代升级中完成 小目标 最终完成那个 大目标 正因为敏捷开发的这种不断迭代升级的开发
  • Window系统查看端口是否启用以及占用程序

    1 打开DOS命令行窗口 开始 gt 运行 gt cmd xff0c 或者是 window 43 R gt cmd xff0c 调出命令窗口 2 查看当前正在使用的所有端口 命令 xff1a netstat ao 包括协议 xff0c 端口
  • ThreadLocal的深度解读

    一 J2SE的原始描述 This class provides thread local variables These variables differ from their normal counterparts in that eac

随机推荐