Skip to content

Exporting to NetworkX

For converting to a networkx graph there is only one function (to_networkx()), which has flags for vertex/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.


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.


import raphtory.export as ex

nx_g = ex.to_networkx(traffic_graph)

print("Networkx graph and the full property history of ServerA:")

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

print("Only the latest properties of ServerA:")


Networkx graph and the full property history of ServerA:
MultiDiGraph with 5 nodes and 7 edges
{'_id': 'ServerA', 'server_name': 'Alpha', 'hardware_type': 'Blade Server', 'datasource': 'data/network_traffic_edges.csv', '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:
{'OS_version': 'Ubuntu 20.04', '_id': 'ServerA', 'primary_function': 'Database', 'server_name': 'Alpha', 'hardware_type': 'Blade Server', 'uptime_days': 120, 'datasource': 'data/network_traffic_edges.csv'}


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.


# 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(
    edges_df=server_edges_df, src="source", dst="destination", time="timestamp"

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