You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Streamlit中集成Gravis可视化?

在Streamlit中嵌入Gravis可视化的解决方案

要将Gravis的图可视化嵌入到Streamlit应用内,核心思路是利用Gravis的HTML导出能力,再通过Streamlit的自定义HTML组件渲染内容,替代默认的fig.display()(该方法在非IPython环境会打开新标签页)。

修改步骤及完整代码

将你代码中的fig.display()替换为以下逻辑:

  1. 通过fig.to_html()获取Gravis可视化的HTML字符串
  2. 使用st.components.v1.html()将HTML嵌入到Streamlit页面中,同时设置合适的高度以完整显示图

修改后的完整代码:

import gravis as gv
import networkx as nx
import streamlit as st
from streamlit.components.v1 import html

st.title("Example")

graph2 = nx.les_miserables_graph()

# Centrality calculation
centrality = nx.algorithms.degree_centrality(graph2)

# Community detection
communities = nx.algorithms.community.greedy_modularity_communities(graph2)

# Assignment of node sizes
nx.set_node_attributes(graph2, centrality, 'size')

# Assignment of node colors
colors = ['red', 'blue', 'green', 'orange', 'pink']
for community, color in zip(communities, colors):
    for node in community:
        graph2.nodes[node]['color'] = color

fig = gv.d3(graph2, use_node_size_normalization=True, node_size_normalization_max=30,
      use_edge_size_normalization=True, edge_size_data_source='weight', edge_curvature=0.3)

# 导出HTML并嵌入到Streamlit
graph_html = fig.to_html()
html(graph_html, height=800, width=None)

关键说明

  • fig.to_html():Gravis提供的方法,直接生成包含可视化逻辑的完整HTML字符串,无需额外依赖
  • html()组件:Streamlit用于嵌入自定义HTML/JS内容的工具,通过设置height参数可以控制可视化区域的高度,避免内容被截断
  • 该方法完全适配Streamlit的页面渲染逻辑,可视化内容会直接显示在应用页面内,不会弹出新标签页

内容的提问来源于stack exchange,提问作者bmfy131

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 11:00:58