0

I'm new to Python. Please help me solve the problem with graph construction. I have a database with the attribute "Source", "Interlocutor" and "Frequency".

An example of three lines:

enter image description here

I need to build a graph based on the Source-Interlocutor, but the frequency is also taken into account.

Like this:

enter image description here

My code:

dic_values={Source:[24120.0,24120.0,24120.0], Interlocutor:[34,34,34],Frequency:[446625000, 442475000, 445300000]
session_graph=pd.DataFrame(dic_values)
friquency=session_graph['Frequency'].unique()
plt.figure(figsize=(10,10))
for i in range(len(friquency)):
   df_friq=session_subset[session_subset['Frequency']==friquency[i]]
   G_frique=nx.from_pandas_edgelist(df_friq,source='Source',target='Interlocutor')
   pos = nx.spring_layout(G_frique)
   nx.draw_networkx_nodes(G_frique, pos, cmap=plt.get_cmap('jet'), node_size = 20)
   nx.draw_networkx_edges(G_frique, pos,  arrows=True)
   nx.draw_networkx_labels(G_frique, pos)
plt.show()  

And I have like this:

enter image description here

prosoitos
  • 6,679
  • 5
  • 27
  • 41
Egor_1811
  • 31
  • 5

1 Answers1

0

Your problem requires a MultiGraph

import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
import pydot
from IPython.display import Image


dic_values = {"Source":[24120.0,24120.0,24120.0], "Interlocutor":[34,34,34],
              "Frequency":[446625000, 442475000, 445300000]}

session_graph = pd.DataFrame(dic_values)
sources = session_graph['Source'].unique()
targets = session_graph['Interlocutor'].unique()


#create a Multigraph and add the unique nodes
G = nx.MultiDiGraph()
for n in [sources, targets]:
    G.add_node(n[0])
    
#Add edges, multiple connections between the same set of nodes okay. 
# Handled by enum in Multigraph    

#Itertuples() is a faster way to iterate through a Pandas dataframe. Adding one edge per row
for row in session_graph.itertuples():
    #print(row[1], row[2], row[3])
    G.add_edge(row[1], row[2], label=row[3])        
        

#Now, render it to a file...
p=nx.drawing.nx_pydot.to_pydot(G)
p.write_png('multi.png')
Image(filename='multi.png') #optional 

This will produce the following:

Graphviz pydot image

Please note that node layouts are trickier when you use Graphviz/Pydot. For example check this SO answer.. I hope this helps you move forward. And welcome to SO.

Ram Narasimhan
  • 22,341
  • 5
  • 49
  • 55