dgl.to_networkx(g, node_attrs=None, edge_attrs=None)[source]

Convert a homogeneous graph to a NetworkX graph and return.

The resulting NetworkX graph also contains the node/edge features of the input graph. Additionally, DGL saves the edge IDs as the 'id' edge attribute in the returned NetworkX graph.

  • g (DGLGraph) – A homogeneous graph.

  • node_attrs (iterable of str, optional) – The node attributes to copy from g.ndata. (Default: None)

  • edge_attrs (iterable of str, optional) – The edge attributes to copy from g.edata. (Default: None)


The converted NetworkX graph.

Return type



The function only supports CPU graph input.


The following example uses PyTorch backend.

>>> import dgl
>>> import torch
>>> g = dgl.graph((torch.tensor([1, 2]), torch.tensor([1, 3])))
>>> g.ndata['h'] = torch.zeros(4, 1)
>>> g.edata['h1'] = torch.ones(2, 1)
>>> g.edata['h2'] = torch.zeros(2, 2)
>>> nx_g = dgl.to_networkx(g, node_attrs=['h'], edge_attrs=['h1', 'h2'])
>>> nx_g.nodes(data=True)
NodeDataView({0: {'h': tensor([0.])},
              1: {'h': tensor([0.])},
              2: {'h': tensor([0.])},
              3: {'h': tensor([0.])}})
>>> nx_g.edges(data=True)
OutMultiEdgeDataView([(1, 1, {'id': 0, 'h1': tensor([1.]), 'h2': tensor([0., 0.])}),
                      (2, 3, {'id': 1, 'h1': tensor([1.]), 'h2': tensor([0., 0.])})])