Hello to all the community,
I'll tell you a little about what I'm doing. I have a table with the following columns as information: "Report Source", "Report" and "Report User" (they have other names in the
dataframe
, but conceptually that's what they mean):
From that information I successfully created a network using the library netwokx
and the visualization framework pyvis
. I attach the code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
import ipywidgets as widgets
from ipywidgets import interact, interact_manual
#Generar Grafo
df1.insert(1, 'ORIGEN', 'ORIGEN')
paths = df1.loc[:,'ORIGEN':].stack().groupby(level=0).agg(list).values.tolist()
G = nx.DiGraph()
for path in paths:
nx.add_path(G, path)
@interact_manual
def grafo(grafo=['neato','dot', 'twopi', 'fdp', 'sfdp', 'circo']):
#return df.loc[df[column] > x]
# Posibilidades para parametro "prog": 'neato',‘dot’, ‘twopi’, ‘fdp’, ‘sfdp’, ‘circo’
pos = graphviz_layout(G, prog= grafo)
plt.figure(figsize=(20, 20))
nx.draw(G, pos= pos,
node_size=40,
alpha=0.5,
node_color="blue",
with_labels=True,
arrows=True)
plt.savefig("dendograma.pdf")
plt.axis("equal")
plt.show()
return
def draw_graph3(networkx_graph,notebook=True,output_filename='graph.html',show_buttons=True,only_physics_buttons=False):
"""
Esta función acepta un objeto gráfico "networkx",
lo convierte en un objeto de red "pyvis" conservando sus atributos de nodo y borde,
y devuelve y guarda una visualización de red dinámica.
Atributos de nodo validos:
"size", "value", "title", "x", "y", "label", "color".
(Para más información: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_node)
Atributos de vertices validos:
"arrowStrikethrough", "hidden", "physics", "title", "value", "width"
(Para más información: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_edge)
Argumentos:
networkx_graph: El gráfico para convertir y mostrar
notebook: ¿Quieres desplegar la visualización en Jupyter Notebook?
output_filename: Ubicación donde se guardara la red convertida
show_buttons: ¿Mostrar botones en la versión guardada de la red?
only_physics_buttons: ¿Mostrar parametros para modificar la red?
"""
# Importacion de librerias
from pyvis import network as net
# Crear una red de pyvis
pyvis_graph = net.Network(notebook=notebook,heading='Fuentes Banco Sabadell', directed = True)
# Para cada nodo y sus atributos en el gráfico networkx
for node,node_attrs in networkx_graph.nodes(data=True):
pyvis_graph.add_node(str(node),**node_attrs, size = 10)
# para cada vertice y sus atributos en el gráfico networkx
for source,target,edge_attrs in networkx_graph.edges(data=True):
# si el valor / ancho no se especifica directamente y se especifica el peso, establezca 'value' en 'weight'
if not 'value' in edge_attrs and not 'width' in edge_attrs and 'weight' in edge_attrs:
# colocar en la clave 'value' el peso del vertice
edge_attrs['value']=edge_attrs['weight']
# agregar el vértice
pyvis_graph.add_edge(str(source),str(target),**edge_attrs, arrowStrikethrough = True )
# agregar botones
if show_buttons:
if only_physics_buttons:
pyvis_graph.show_buttons(filter_=['physics'])
else:
pyvis_graph.show_buttons()
# regresar grafo y guardar
return pyvis_graph.show(output_filename)
# Llamada a la función
draw_graph3(G, only_physics_buttons=True)
Giving me the following network as output:
However, what I want to achieve is that the source node has a different color, the source nodes have a different color, the report nodes have a different color and finally the last user nodes have a different color to improve the graph. Any idea how I could achieve it?
Cheers!
In the end I just had to add these lines inside the function
draw_graph3
to get what I was looking for:This was the incredible result: