Skip to content

Exporting to NetworkX

For converting to a networkx graph there is only one function (to_networkx()), which has flags for node/edge history and for exploding edges. By default all history is included and the edges are separated by layer.

In the below code snippet we call to_networkx() on the network traffic graph, keeping all the default arguments and, therefore, exporting the full history. We have extracted ServerA from this graph and printed it so that you may see how the history is modelled.

Info

Note that the resulting graph is a networkx MultiDiGraph as Raphtory graphs are both directed and have multiple edges between nodes.

We then call to_networkx() again, disabling the property/update history and reprint ServerA allowing you to see the difference.

Graph

nx_g = traffic_graph.to_networkx()

print("Networkx graph:")
print(nx_g)
print()
print("Full property history of ServerA:")
print(nx_g.nodes["ServerA"])
print()

nx_g = traffic_graph.to_networkx(include_property_history=False)

print("Only the latest properties of ServerA:")
print(nx_g.nodes["ServerA"])

Output

Networkx graph:
MultiDiGraph with 5 nodes and 7 edges

Full property history of ServerA:
{'constant': {'server_name': 'Alpha', 'hardware_type': 'Blade Server', 'datasource': 'data/network_traffic_edges.csv'}, 'temporal': [('OS_version', (1693555200000, 'Ubuntu 20.04')), ('primary_function', (1693555200000, 'Database')), ('uptime_days', (1693555200000, 120))], 'update_history': [1693555200000, 1693555500000, 1693556400000]}

Only the latest properties of ServerA:
{'server_name': 'Alpha', 'hardware_type': 'Blade Server', 'uptime_days': 120, 'OS_version': 'Ubuntu 20.04', 'primary_function': 'Database', 'datasource': 'data/network_traffic_edges.csv', 'update_history': [1693555200000, 1693555500000, 1693556400000]}

Visualisation

Once converted into a networkX graph you are free to use their full suite of functionality. One great use of this conversion is to make use of their drawing library for visualising graphs.

In the code snippet below we use this functionality to draw the network traffic graph, labelling the nodes with their Server ID. These visualisations can become as complex as your like, but we refer you to the networkx documentation for this.

Graph

# mkdocs: render
import matplotlib.pyplot as plt
import networkx as nx

from raphtory import Graph
import pandas as pd

server_edges_df = pd.read_csv("data/network_traffic_edges.csv")
server_edges_df["timestamp"] = pd.to_datetime(server_edges_df["timestamp"])

traffic_graph = Graph.load_from_pandas(
    edge_df=server_edges_df,
    edge_src="source",
    edge_dst="destination",
    edge_time="timestamp",
)

nx_g = traffic_graph.to_networkx()
nx.draw(nx_g, with_labels=True, node_color="lightblue", edge_color="gray")