如何在Streamlit中通过HTML将Plotly图表对齐至页面中心
问题描述

原有绘图代码如下:
import pandas as pd import streamlit as stl def plot_open_close_chart(dataframe: pd.DataFrame, name: str, start_date: int, end_date: int) -> stl.plotly_chart: fig = dataframe.iplot(y="Open", secondary_y="Close", secondary_y_title="Close Price ($)", xTitle="Date", yTitle="Open Price ($)", title=f'''Open and Close Price of {name} From {start_date} To {end_date}''', asFigure=True) stl.plotly_chart(fig) get_record_low_and_high(dataframe, dataframe.Close)
遇到的问题:参照页面下方Record Low模块的HTML居中写法调整Plotly图表样式不生效,直接将fig对象写入HTML代码无法渲染出图表,需要可行的Plotly图表居中方案。
解决方案
不需要手写HTML拼接实现居中,Streamlit对Plotly图表有原生支持,两种方案可直接使用:
- 方案1:使用组件自带参数(推荐,Streamlit 1.20+版本支持)
直接给stl.plotly_chart传入对齐参数即可实现居中,不需要额外布局代码。如果需要自定义图表宽度,可先通过fig.update_layout(width=自定义宽度值)设置图表固定宽度。修改后的代码如下:def plot_open_close_chart(dataframe: pd.DataFrame, name: str, start_date: int, end_date: int) -> stl.plotly_chart: fig = dataframe.iplot(y="Open", secondary_y="Close", secondary_y_title="Close Price ($)", xTitle="Date", yTitle="Open Price ($)", title=f'''Open and Close Price of {name} From {start_date} To {end_date}''', asFigure=True) # 关闭容器全宽,设置居中对齐 stl.plotly_chart(fig, use_container_width=False, align="center") get_record_low_and_high(dataframe, dataframe.Close) - 方案2:列布局兼容方案(适配低版本Streamlit)
如果使用的Streamlit版本低于1.20,没有align参数,可以通过三列布局,左右设置等宽空列占位,中间列放置图表实现居中效果,可通过调整三列的宽度占比控制图表显示宽度:def plot_open_close_chart(dataframe: pd.DataFrame, name: str, start_date: int, end_date: int) -> stl.plotly_chart: fig = dataframe.iplot(y="Open", secondary_y="Close", secondary_y_title="Close Price ($)", xTitle="Date", yTitle="Open Price ($)", title=f'''Open and Close Price of {name} From {start_date} To {end_date}''', asFigure=True) # 三列宽度占比1:4:1,左右留空,中间放图表 _, center_col, _ = stl.columns([1, 4, 1]) with center_col: stl.plotly_chart(fig, use_container_width=True) get_record_low_and_high(dataframe, dataframe.Close)
注意:Plotly的fig对象是Python类实例,直接写入HTML代码只会输出对象的字符串标识,无法渲染为可视化图表,必须通过Streamlit官方提供的
plotly_chart组件完成渲染。
内容的提问来源于stack exchange,提问作者Jamiu S.
相关产品推荐
相关产品推荐

