如何让Plotly与NiceGUI良好协作?绑定数据刷新图表遇问题求助
问题解决:绑定数字列表到字典并刷新Plotly图表
问题根源
你使用ui.input直接绑定到字典的x和y字段,但ui.input的输入内容默认是字符串类型,而非数字列表。这就导致coords['x']和coords['y']实际存储的是字符串,不是你需要的列表格式,进而让Plotly图表无法正确读取数据。
修复后的代码
from nicegui import ui import plotly.graph_objects as go coords = {'x': [], 'y': []} def str_to_num_list(s): # 将逗号分隔的字符串转换为数字列表,处理空输入和非数字情况 try: return [float(num.strip()) for num in s.split(',') if num.strip()] except ValueError: return [] # 绑定输入时通过transform参数转换字符串为数字列表 ui.input(label='X', value='1, 2, 3, 4').bind_value_to(coords, 'x', transform=str_to_num_list) ui.input(label='Y', value='1, 2, 3, 4').bind_value_to(coords, 'y', transform=str_to_num_list) fig = go.Figure(go.Scatter(x=coords['x'], y=coords['y'])) fig.update_layout(margin=dict(l=0, r=0, t=0, b=0)) plot = ui.plotly(fig).classes('w-full h-40') def update_plt(): fig.data = [] x2 = coords['x'] y2 = coords['y'] # 确保x和y列表长度一致,避免Plotly报错 min_length = min(len(x2), len(y2)) fig.add_trace(go.Scatter(x=x2[:min_length], y=y2[:min_length])) plot.update() ui.button('Refresh', on_click=update_plt) ui.run()
关键修改点
- 添加类型转换函数:
str_to_num_list将用户输入的逗号分隔字符串(比如"1, 2, 3")转换为数字列表[1.0, 2.0, 3.0],同时处理空输入和无效数字的异常情况。 - 绑定参数
transform:在bind_value_to中使用transform参数,自动将输入字符串转换为数字列表后再存入字典。 - 长度一致性处理:在更新图表时,取x和y列表的较短长度,避免因两个列表长度不一致导致Plotly渲染报错。
内容的提问来源于stack exchange,提问作者DrewGIS
相关产品推荐
相关产品推荐

