Liu/main.py

100 lines
2.5 KiB
Python
Raw Normal View History

2024-02-20 09:20:41 +08:00
# Import packages
from dash import Dash, dcc, html, Input, Output
import feffery_antd_components as fac
import plotly.graph_objs as go
from listen import VoltageReceiver
def read_from_file(filename):
"""
This function read data from a local .txt file
:param filename: str, name of the file
:return: str, data read from the file
"""
with open(filename, 'r') as file:
data = file.read().replace('\n', '')
return data
def write_to_file(data, filename):
"""
This function write data to a local .txt file
:param data: str, data to be written to the file
:param filename: str, name of the file
"""
with open(filename, 'w') as file:
file.write(data)
def go_figure_set(X, Y, figuremode, width=600, height=400, title=''):
# 创建折线图
line_chart = go.Figure(data=go.Scatter(x=X, y=Y, mode=figuremode))
line_chart.update_layout(
autosize=False,
width=width,
height=height,
title=title
)
return line_chart
# Initialize the app
app = Dash(__name__)
X = list(range(1, 1001))
Y = [0] * 1000
# App layout
app.layout = html.Div(
[
html.Div([
dcc.Graph(
id='line-chart',
figure=go_figure_set(X, Y, 'lines'),
)], style={
'display': 'inline-block',
'position': 'absolute', # 使用绝对定位
'right': '20px', # 距离页面右边20px
'top': '20px', # 距离页面顶部20px
'width': '600px' # 设置图表容器的宽度
}), # 将折线图添加到Dash应用中
dcc.Interval(
id='interval-update',
interval=1*10, # in milliseconds
),
],
style={
'padding': '50px 100px'
},
)
# Define callback to update statistic
@app.callback(
Output('line-chart', 'figure'),
Input('interval-update', 'n_intervals')
)
def update_output(n_intervals):
data = read_from_file('test.txt')
if data == '#':
pass
else:
Y.append(float(data))
Y.pop(0)
write_to_file('#', "test.txt")
line_chart = go_figure_set(X, Y, 'lines')
# 更新图表布局设置新的X轴范围
line_chart.update_layout(xaxis=dict(range=[0, 2001]))
line_chart.add_trace(go.Scatter(x=list(range(1001, 1051)), y=list(range(1, 51)), mode='lines',line=dict(color='red')))
return line_chart
# Run the app
if __name__ == '__main__':
app.run_server(debug=True, port=8050)