Plotly配合Streamlit开发时如何保持choropleth地图默认全屏展示
解决方案
方案1:原生自适应布局(最稳定,推荐使用)
你不需要强制触发Plotly的全屏功能,只需要调整两处代码即可实现地图自适应屏幕宽度、居中展示,效果和全屏查看几乎一致,且兼容性更好:
- 删除Plotly布局中的固定宽高设置,开启自动尺寸,同时去掉多余留白:
把原来的fig.update_layout(autosize=False, width= 1200, height=800)替换为:
fig.update_layout(autosize=True, margin=dict(l=0, r=0, t=0, b=0))
- 调用Streamlit渲染图表时开启容器宽度适配,把最后一行
st.plotly_chart(fig)替换为:
st.plotly_chart(fig, use_container_width=True)
修改后地图会自动占满当前页面的全部可用宽度,自动居中,不同尺寸的设备打开都会自适应调整大小,完全满足你的需求。
方案2:默认触发Plotly全屏状态
如果你确实需要页面加载后直接进入和工具栏「全屏查看」完全一致的状态,可以通过注入少量JS实现,完整代码如下:
import streamlit as st import pandas as pd import plotly.express as px import streamlit.components.v1 as components # 原有数据处理逻辑保持不变 vaccination_data = pd.read_csv('vaccinations.csv') df = pd.DataFrame(vaccination_data) def vaccination_lastest_date_by_country(df): return df.groupby('location').last().reset_index() country_lastest_vaccination = vaccination_lastest_date_by_country(df) df_vaccination_by_country = country_lastest_vaccination.sort_values(by='total_vaccinations_per_hundred', ascending=True) fig = px.choropleth(df_vaccination_by_country, locations="iso_code", color="total_vaccinations_per_hundred", hover_name="location", color_continuous_scale=px.colors.sequential.Plasma) fig.update_layout(autosize=True) # 渲染图表时指定唯一key st.plotly_chart(fig, use_container_width=True, key="vaccine_map") # 注入JS自动触发全屏 components.html( """ <script> const fullscreenBtn = parent.document.querySelector('a[title="Full screen"]'); if (fullscreenBtn) fullscreenBtn.click(); </script> """, height=0 )
注意该方案依赖Plotly工具栏的DOM结构,Plotly版本更新后可能需要调整选择器适配。
内容的提问来源于stack exchange,提问作者Woden
相关产品推荐
相关产品推荐

