PySimpleGUI与Matplotlib的集成:动态显示数据
2024.01.17 14:03浏览量:14简介:介绍如何使用PySimpleGUI和Matplotlib进行集成,实现动态显示数据。通过简单的代码示例,帮助读者快速上手。
千帆应用开发平台“智能体Pro”全新上线 限时免费体验
面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用
PySimpleGUI是一个用于创建图形用户界面的Python库,而Matplotlib则是一个用于绘制图表和图形的库。通过将这两个库进行集成,我们可以创建动态更新的图表和图形,为用户提供更直观的数据展示。
下面是一个简单的示例,演示如何使用PySimpleGUI和Matplotlib进行集成,动态显示数据:
```python
import matplotlib.pyplot as plt
import numpy as np
import PySimpleGUI as sg
创建简单的数据
data = np.random.rand(100)
创建PySimpleGUI窗口布局
layout = [[sg.Column([[sg.Text(‘动态数据’)]], pad=(0,0))],
[[sg.Graph(canvas_size=(500, 500), graph_bottom_left=(0, 0), graph_top_right=(500, 500), background_color=’white’, line_color=’blue’, fill_color=’lightblue’)]],
[[sg.Text(‘数据范围:’, pad=(0,0))],
[sg.Input(size=(40, 1), key=’-DATA-RANGE-‘, enable_events=True, enable_undo=False, expand_to_width=True, input_color=’black’)]],
[[sg.Text(‘更新频率:’, pad=(0,0))],
[sg.Input(size=(40, 1), key=’-UPDATE-FREQ-‘, enable_events=True, enable_undo=False, expand_to_width=True, input_color=’black’)]],
[[sg.Text(‘数据:’, pad=(0,0))],
[sg.Text(size=(40, 1), key=’-DATA-‘, enable_events=True, enable_undo=False, expand_to_width=True, input_color=’black’)]],
[[sg.Graph(canvas_size=(500, 500), graph_bottom_left=(0, 0), graph_top_right=(500, 500), background_color=’white’, line_color=’blue’, fill_color=’lightblue’)]]]
创建PySimpleGUI窗口
window = sg.Window(‘动态数据展示’, layout, margins=(0,0), finalize=True)
初始化图表和数据
plt.ion() # 开启交互模式
plt.figure(figsize=(5,5)) # 设置图表大小
plt.plot(data) # 绘制数据
plt.xlim(0, len(data)) # 设置x轴范围
plt.ylim(-1, 1) # 设置y轴范围
plt.gca().set_title(‘动态数据’) # 设置图表标题
plt.gca().set_xlabel(‘数据索引’) # 设置x轴标签
plt.gca().set_ylabel(‘数据值’) # 设置y轴标签
plt.gca().grid(True) # 显示网格线
plt.gcf().canvas.draw() # 刷新图表
window[‘-GRAPH-‘].expand(True) # 展开图表区域
window[‘-DATA-‘].expand(True) # 展开数据区域
window[‘-UPDATE-FREQ-‘].expand(True) # 展开更新频率区域
window[‘-DATA-RANGE-‘].expand(True) # 展开数据范围区域
处理事件循环
while True:
event = window.read()
if event == sg.WIN_CLOSED: # 如果窗口被关闭,退出循环
break
elif event == ‘-DATA-RANGE-‘: # 如果输入了数据范围,更新图表范围
plt.xlim(*event.split(‘:’)[1].split(‘-‘)) # 使用冒号分隔输入字符串,再使用破折号分隔得到范围值
plt.gcf().canvas.draw() # 刷新图表
elif event == ‘-UPDATE-FREQ-‘: # 如果输入了更新频率,根据频率更新数据并重绘图表
update_freq = int(event) # 将输入的频率转换为整数
for i in range(update_freq): # 根据频率循环更新数据并重绘图表
data = np.random.rand(100) # 生成随机数据
plt.plot(

发表评论
登录后可评论,请前往 登录 或 注册