Search code examples
pythonstreamlit

How to integrate Gravis visualization inside of Streamlit?


Hello I want to understand how I can visualize graph databases using Gravis inside of a Streamlit app.

Here is a link to gravis: https://robert-haas.github.io/gravis-docs/index.html

So far I've been able to launch the Streamlit app then it opens the app in a localhost browser tab, and then for the gravis visualization it opens a separate browser tab. I would like for this gravis visualization to appear inside the streamlit app itself but can't figure out how to integrate the two. I understand that this is easy inside a IPython style notebook but harder for a Streamlit app.

Any help is appreciated

Here is my code (anyone should be able to run it by running: streamlit run app.py):

import gravis as gv
import networkx as nx
from datetime import datetime
import streamlit as st

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)

fig.display()

Is there a way to wrap the visualized and nest it inside of the streamlit app?

Thank you


Solution

  • You can create an HTML repr of the graph with to_html, then render it inside components :

    # fig.display() # remove this line
    
    import streamlit.components.v1 as components
    
    components.html(fig.to_html(), height=600) # << adjust if needed
    

    Preview (at http://localhost:8501/) :

    enter image description here