Streamlit and visualization of network(x) structures

Hi,

Q 1)
I am entirely new to actual use of Streamlit. The functionality looks very promising to me.

Right now I am in the process of creating mockup in python. Yet looking into the various chart options ( Chart elements - Streamlit Docs), and following Streamlit, I do not seem to spot a visualisation rendering a network(x) infrastructure.

Is that because:

  • I am lacking imagination? …use e.g. plotly to display?

  • There is no option available?

Q 2)
I am a bit in doubt when using Streamlit. I did create my app.py file using the command prompt and things do seem to work, somehow. Still, trying to visualize (and maybe this points back to Q 1, above) I am not able to make the structures appear, e.g. using the below code (‘stolen’ from a tutorial elsewhere on the internet). Basically, this code ONLY provides plotly bars, representing the input provides by user, i.e. NO network structure comes from below code. It is merely intended for me to see, how I can make things happen with Streamlit (…and network(x)), In conclusion: Executing my app.py works fine, presenting charts doesn’t.

def nodes_and_edges():
a = int(input("Enter counter value 1: "))
b = int(input("Enter counter value 2: "))
c = int(input("Enter counter value 3: "))
test_a, test_b, test_c = , ,
# test_b =
# test_c =
i, j, k = 0, 0, 0
# j=0
# k=0
while i < a:
pl = int(input(“Enter item value 1:”))
test_a.append(pl)
i += 1
# print(list(test_a))
while j < b:
p2 = int(input("Enter item value 2: "))
test_b.append(p2)
j += 1
# print(list(test_b))
while k < c:
try:
p3 = int(input("Enter item value 3: "))
test_c.append(p3)
k += 1
except ValueError:
print(“Please input int only…”)

one = nodes_and_edges()

print("\none")
print(one)

user_input = tuple(one.itertuples(index=False, name=None))
interactions = user_input

G=nx.Graph(name=‘xxx Interaction Test Graph’)
interactions = np.array(interactions)
for i in range(len(interactions)):
interaction = interactions[i]
a = interaction[0] # source node
b = interaction[1] # destination node
w = float(interaction[2]) # score as weighted edge where high scores = low weight
G.add_weighted_edges_from([(a,b,w)]) # add weighted edge to graph

x1 = G.nodes(interactions[0])
x2 = G.nodes(interactions[1])
x3 = G.nodes(interactions[2])

Group data together

hist_data = [x1, x2, x3]

group_labels = [‘Value 1’, ‘value 2’, ‘Value 3’]

Create distplot with custom bin_size

fig = ff.create_distplot(hist_data, group_labels, bin_size=[.1, .25, .5])

Plot!

st.plotly_chart(fig, use_container_width=True)

Looking very much forward to learning your reply.

BR

Jens Steenfos, Copenhagen, Denmark
The Newbie

Hi @projectfreak, welcome to the Streamlit community!

It’s not currently in the documentation, but please see this article how to use Networkx and Streamlit:

Best,
Randy

3 Likes

Hey @projectfreak, please also check the code in this example.

import streamlit as st
import networkx as nx
import matplotlib.pyplot as plt

st.title('Hello Networkx')
st.markdown('Zachary´s Karate Club Graph')


G = nx.karate_club_graph()


fig, ax = plt.subplots()
pos = nx.kamada_kawai_layout(G)
nx.draw(G,pos, with_labels=True)
st.pyplot(fig)
st.balloons()

I also added an example at the end of this tutorial for using Pyvis (though it is in Spanish).
Here is the app for that case:
https://share.streamlit.io/napoles-uach/pycon_cl_taller/main/appGraph/appGraph.py

Hope this helps!!

1 Like

Hi, what you forwarded to me is absolutely gold…;o))

What I need now is to do as follows:

  • Integrate my def nodes_and_edges() with the code I received from you, i.e. I want to be able to translate the input made in aforementioned function to nodes and edges and weights. I found below tutorial that I want to pair with already subnmitted code.

def nodes_and_edges():
a = int(input("Enter counter value 1: "))
b = int(input("Enter counter value 2: "))
c = int(input("Enter counter value 3: "))
test_a, test_b, test_c = , ,
i, j, k = 0, 0, 0
while i < a:
pl = int(input(“Enter item value 1:”))
test_a.append(pl)
i += 1
while j < b:
p2 = int(input("Enter item value 2: "))
test_b.append(p2)
j += 1
while k < c:
try:
p3 = int(input("Enter item value 3: "))
test_c.append(p3)
k += 1
except ValueError:
print(“Please input int only…”)
DF1 = pd.DataFrame(test_a)
print(DF1.nunique())
DF2 = pd.DataFrame(test_b)
print(DF2.nunique())
DF3 = pd.DataFrame(test_c)
print(DF3.nunique())
DF4 = pd.concat([DF1, DF2, DF3], axis=1, ignore_index=True)
DF4.columns = [‘Value1_Col’, ‘Value2_Col’, ‘Value3_Col’]
return DF4

one = nodes_and_edges()

print("\none")
print(one)

user_input = tuple(one.itertuples(index=False, name=None))
interactions = user_input

G=nx.Graph(name=‘GridWit Interaction Test Graph’)
interactions = np.array(interactions)

How do I make below ‘inject’ data from the above, creating a network where ONLY USER KEYBOARD INPUT defines nodes and edges interpreted in below code. I keep getting assertion error, because ‘nt.from_nx(nx_graph)’

from pyvis.network import Network
import matplotlib.pyplot as plt
import networkx as nx
nx_graph = nx.cycle_graph(10) # tried => nx_graph = G, but I get assertion error!!
nx_graph.nodes[1][‘title’] = ‘Number 1’
nx_graph.nodes[1][‘group’] = 1
nx_graph.nodes[3][‘title’] = ‘I belong to a different group!’
nx_graph.nodes[3][‘group’] = 10
nx_graph.add_node(20, size=20, title=‘couple’, group=2)
nx_graph.add_node(21, size=15, title=‘couple’, group=2)e
nx_graph.add_edge(20, 21, weight=5)
nx_graph.add_node(25, size=25, label=‘lonely’, title=‘lonely node’, group=3)
nt = Network(‘500px’, ‘500px’)
nt.from_nx(nx_graph)
nt.show(‘nx.html’)
plt.show()

  • Make it look like the fabulous Add node streamlit example you forwarded as well

H, Napoles - I spent a lot of time understanding why my browser keeps opening a new window for every time I add a new node. I am referring to the streamlit app on continuously adding new nodes (that you forwarded).

What am I doing wrong. Other than that I am very thankful to you for your response to me on my issue. BR projectfreak

Hi @projectfreak, that doesn’t happen on my side, but I know that some users have experienced similar behavior (not with this example, but in other cases)
The trick I use here to render the Pyvis graph is to write an HTML file, that is shown with components.html. Have you tried components.html in other cases? and if so, do you have experienced the same behavior?

A user claimed that this can be solved using net.Network(notebook=True, …)

Hi José, the ‘net.Network(notebook=True)’-solution was in fact part of my approach, too. Yet looking into the code I am a bit in doubt where to apply this. Can you elaborate? BR projectfreak

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.