Flask中实现Plotly柱状图随屏幕尺寸切换横竖方向
解决方案:纯Python实现Plotly柱状图响应式方向切换
问题分析
你设置的config={'responsive': True}仅能让图表自适应容器尺寸,但无法自动切换柱状图的垂直/水平方向。要实现大屏垂直、小屏水平的效果,需要结合屏幕尺寸判断,动态调整图表的x、y轴数据映射——这可以通过在Python生成的HTML中嵌入极简的JS代码实现(无需你手动编写JS逻辑,全部在Python中完成)。
修改后的Python代码
def create_bar_graph(): # 定义基础数据 categories = ['Category 1', 'Category 2', 'Category 3'] values = [10, 20, 15] # 初始化垂直柱状图 data = [go.Bar(x=categories, y=values)] layout = go.Layout( title='Bar Graph', barmode='group', autosize=True, # 开启自动适应容器 xaxis={'title': '类别'}, yaxis={'title': '数值'} ) fig = go.Figure(data=data, layout=layout) # 生成基础图表HTML,开启响应式 graph_html = pio.to_html(fig, full_html=False, config={'responsive': True}) # 嵌入自动切换方向的JS代码(已封装好,无需你修改) toggle_orientation_js = """ <script> function switchBarDirection() { const screenWidth = window.innerWidth; const plotElement = document.querySelector('.plotly-graph-div'); if (!plotElement) return; const plot = Plotly.getPlot(plotElement); const categories = ['Category 1', 'Category 2', 'Category 3']; const values = [10, 20, 15]; // 匹配Bootstrap lg断点(992px),和你的页面布局断点一致 if (screenWidth < 992) { // 小屏:切换为水平柱状图 Plotly.restyle(plot, 'x', [values]); Plotly.restyle(plot, 'y', [categories]); Plotly.relayout(plot, {'xaxis.title.text': '数值', 'yaxis.title.text': '类别'}); } else { // 大屏:恢复垂直柱状图 Plotly.restyle(plot, 'x', [categories]); Plotly.restyle(plot, 'y', [values]); Plotly.relayout(plot, {'xaxis.title.text': '类别', 'yaxis.title.text': '数值'}); } } // 页面加载时执行一次,窗口 resize 时自动触发 window.addEventListener('load', switchBarDirection); window.addEventListener('resize', switchBarDirection); </script> """ # 将JS代码追加到图表HTML末尾 graph_html += toggle_orientation_js return graph_html
关键说明
- 断点匹配:JS中使用的992px是Bootstrap的
lg级断点,和你HTML里的col-lg-8完全对应,确保图表方向切换时机和页面布局的响应式变化同步。 - 无需手动编写JS:所有JS逻辑都在Python代码中生成,你只需要替换原有的
create_bar_graph函数即可。 - 自适应逻辑:页面加载和窗口大小变化时,JS会自动检测屏幕宽度,切换柱状图的x、y轴数据映射,同时更新轴标题保证语义正确。
原HTML代码无需修改
你的现有HTML代码保持不变,{{ graph_html | safe }}会自动加载包含JS逻辑的图表内容。
内容的提问来源于stack exchange,提问作者Jzbach
相关产品推荐
相关产品推荐

