streamlit自定义图表大小 (用components渲染pyecharts等)

发布于:2022-12-17 ⋅ 阅读:(1261) ⋅ 点赞:(0)

        streamlit能够很方便地将图表渲染在网页上,所以可以很方便地部署在服务器上。但是它渲染图表时,默认宽高无法改变,这就为用户想更清晰地了解数据情况设置了一定的障碍。

        本文使用components渲染pyecharts图表,从而实现了图表自定义大小。

先看效果:

        上方折线图是用普通方式添加的,无法自定义宽高,下图是用components渲染的,可以自定义高度。

        第一幅图是streamlit默认的方法添加,代码:

import streamlit_echarts

from pyecharts.charts import Line
from pyecharts import options as opts

columns = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
line = Line().add_xaxis(columns)

line.width = '1000px'
data1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
data2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
line.add_yaxis(series_name="降水量", y_axis=data1, label_opts=opts.LabelOpts(is_show=True))
line.add_yaxis(series_name="蒸发量", y_axis=data2, label_opts=opts.LabelOpts(is_show=True))

streamlit_echarts.st_pyecharts(
            line
        )

这种方法,仅仅是将pyecharts的图当做完整的组件整体添加,效果如下图,比较扁平。 

         而修改后的代码,将pyecharts的折线图,先转换成html文本,然后再用components添加,就能够实现自定义组件的大小了。

import streamlit_echarts
from pyecharts.charts import Line
from pyecharts import options as opts
import streamlit.components.v1 as components        #将要展示的 弄成html

line2 = Line().add_xaxis(columns)
line2.height = '550px'  # 设置高度
line2.width = '900px'
data1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
data2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
line2.add_yaxis(series_name="降水量", y_axis=data1, label_opts=opts.LabelOpts(is_show=True))
line2.add_yaxis(series_name="蒸发量", y_axis=data2, label_opts=opts.LabelOpts(is_show=True))
line2Html = line2.render_embed()            #将折线组件转换成html文本
components.html(line2Html,height=900, width=900)          #在主页面用streamlit静态组件的方式渲染pyecharts

        效果如下图,很显然,它高了许多。

         使用components渲染pyecharts图表,从而实现了图表自定义大小。

参考资料:

https://www.jianshu.com/p/554d64470ec9

https://pyecharts.org/#/zh-cn/rectangular_charts?id=line:折线面积图

https://docs.streamlit.io/library/components/components-api


网站公告

今日签到

点亮在社区的每一天
去签到