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

import raphtory.export as ex

nx_g = ex.to_networkx(traffic_graph)

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

nx_g = ex.to_networkx(
    traffic_graph, include_property_histories=False, include_update_history=False
)

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

Output

Networkx graph and the full property history of ServerA:
MultiDiGraph with 5 nodes and 7 edges
{'server_name': 'Alpha', 'hardware_type': 'Blade Server', 'datasource': 'data/network_traffic_edges.csv', 'primary_function': [(1693555200000, 'Database')], 'uptime_days': [(1693555200000, 120)], 'OS_version': [(1693555200000, 'Ubuntu 20.04')], 'update_history': [1693555200000, 1693555500000, 1693556400000]}

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

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 raphtory.export as ex
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"]).astype(
    "datetime64[ms, UTC]"
)

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

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