Streamlit-ECharts
Streamlit-ECharts是一个Streamlit组件,用于在Python应用程序中展示ECharts图表。ECharts是一个由百度开发的JavaScript数据可视化库Apache ECharts
安装模块库
pip install streamlit
pip install streamlit-echarts
绘制热力图展示
在基础热力图上拓展了tooltip提示信息,如图所示,基础热力图绘制数据为[0, 0, 5],现需要将tooltip提示信息增加一个label,故源数据可能变为[0, 0, 5, ‘A’],此时在不改变热力图绘制的前提下,拓展提示信息
实现代码(详细注释)
程序结构如下图:
heatmap.py程序如下:
from streamlit_echarts import st_echarts
from streamlit_echarts import JsCode
def render_basic_heatmap(x_data, y_data, v_data):
data = v_data
# 从 v_data 中提取绘制热力图需要的数据,即每个数据点的x、y坐标和值
heatmap_data = [[row[0], row[1], row[2]] for row in data]
# 定义ECharts的配置选项(即ECharts的option)
option = {
# 设置图表的提示信息,当鼠标悬停在数据点上时显示
"tooltip": {
"position": "top", # 提示框位置在数据点上方
'trigger': 'item', # 提示触发方式为单个数据点
# 使用JsCode来编写自定义的提示格式化函数
'formatter': JsCode(
"function (param) {
const originalData = %s.find(d => d[0] === param.data[0] && d[1] === param.data[1] && d[2] === param.data[2]);\
const temp = originalData ? originalData[3] : 'N/A';\
return ['x: '+param.data[0],'y: '+param.data[1], 'value: '+param.data[2], 'label: '+temp].join('<br/>')}" % data
).js_code}, # 将字符串转换为JavaScript代码
"grid": {
"height": "50%", "top": "10%"}, # 设置网格,这里设置网格高度为50%,顶部留出10%
# 数据缩放,设置为内缩,垂直方向
"dataZoom": [{
"type": 'inside',
"orient": 'vertical',
},{
"type": 'inside',
}],
# x轴配置,类型为类别轴,启用分隔区域
"xAxis": {
"type": "category", "data": x_data, "splitArea": {
"show": True}},
# y轴配置,类型为类别轴,启用分隔区域
"yAxis": {
"type": "category", "data": y_data, "splitArea": {
"show": True}},
# 设置视觉映射,用于颜色映射
"visualMap": {
"min": 0,
"max": 10,
"calculable": True,
"orient": "horizontal",
"left": "center",
"bottom": "10%"
},
"series": [
{
"name": "CIC Value",
"type": "heatmap", # 图表类型为热力图
"data": heatmap_data,
"emphasis": {
# 高亮样式
"itemStyle": {
"shadowBlur": 10, "shadowColor": "rgba(0, 0, 0, 0.5)"}
}
}
],
}
st_echarts(option, height="500px") # 渲染图表
app.py程序如下:
import streamlit as st
from heatmap import render_basic_heatmap
data = [[0, 0, 5, 'A'], [0, 1, 1, 'B'], [0, 2, 0, 'C'], [0, 3, 0, 'D'], [0, 4, 0, 'E'], [0,<