python web框架streamlit(st)(二)
文章目录实现油量仪表盘实现散点图-原生实现散点图-Plotly(推荐)内容太多了拆出一篇。实现油量仪表盘就是换个组件而已。创建fuel_indicator.py(油量仪表盘)(燃料指示器)代码importstreamlitasstimportplotly.graph_objectsasgoimportnumpyasnpimporttime# --- 1. 页面配置 ---st.set_page_config(page_title油门监控,layoutwide)st.title(️ 实时油门监控 (去Key版))# --- 2. 创建占位符 ---gauge_placeholderst.empty()trend_placeholderst.empty()# --- 3. 模拟数据逻辑 ---current_val50history_data[50]# --- 4. 绘图函数 ---defdraw_gauge(value):figgo.Figure(go.Indicator(modegaugenumber,valuevalue,domain{x:[0,1],y:[0,1]},title{text:实时负载 (油门深度)},gauge{axis:{range:[None,100]},bar:{color:#FF4B4B},steps:[{range:[0,50],color:#e0e0e0},{range:[50,80],color:#c0c0c0},{range:[80,100],color:#a0a0a0}],threshold:{line:{color:red,width:4},thickness:0.75,value:90}}))fig.update_layout(height300,margindict(l20,r30,t40,b20))returnfigdefdraw_trend(data):figgo.Figure()fig.add_trace(go.Scatter(ydata,modelines,filltozeroy,linedict(color#1f77b4,width3)))fig.update_layout(height200,margindict(l20,r20,t20,b20),xaxisdict(visibleFalse),yaxisdict(range[0,110],visibleFalse))returnfig# --- 5. 循环 ---whileTrue:# 1. 计算新数据targetnp.random.choice([10,30,50,80,95,10],p[0.2,0.2,0.2,0.2,0.1,0.1])current_valcurrent_val(target-current_val)*0.2history_data.append(round(current_val,1))iflen(history_data)50:history_data.pop(0)# 2. 更新界面 (已移除 key 参数)withgauge_placeholder.container():st.plotly_chart(draw_gauge(current_val),use_container_widthTrue)# 这里删掉了 keyifcurrent_val90:st.error(⚠️ 警告过载)else:st.success(✅ 运行平稳)withtrend_placeholder.container():st.plotly_chart(draw_trend(history_data),use_container_widthTrue)# 这里删掉了 key# 3. 暂停time.sleep(0.2)实现散点图-原生创建scatter_plot(散点图)代码importstreamlitasstimportpandasaspdimportnumpyasnp# 1. 准备数据dfpd.DataFrame(np.random.randn(100,2),columns[x,y])# 2. 一行代码画图st.title(原生散点图)st.scatter_chart(df,xx,yy)实现散点图-Plotly(推荐)如果要专业点用plotly更快捷方便功能更强大。创建scatter_plot_plotly.py代码importstreamlitasstimportplotly.expressaspximportpandasaspdimportnumpyasnp# 1. 准备数据 (模拟鸢尾花数据)dfpd.DataFrame({sepal_length:np.random.randn(100)5,sepal_width:np.random.randn(100)3,category:np.random.choice([A类,B类],100)})st.title(Plotly 交互式散点图)# 2. 使用 Plotly Express 画图figpx.scatter(df,xsepal_length,ysepal_width,colorcategory,# 按类别着色sizesepal_length,# 点的大小随数值变化hover_data[sepal_width]# 鼠标悬停时显示的信息)# 3. 在 Streamlit 中展示st.plotly_chart(fig,use_container_widthTrue)
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2492202.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!