2
%matplotlib inline
import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_node('abc@gmail.com')
nx.draw(G, with_labels=True)
plt.show()

The output figure is

enter image description here

What I want is

enter image description here

I have thousands of email records from person@email.com to another@email.com in a csv file, I use G.add_node(email_address) and G.add_edge(from, to) to build G. I want keep the whole email address in Graph G but display it in a simplified string.

Adelin
  • 7,809
  • 5
  • 37
  • 65
Animeta
  • 1,241
  • 3
  • 16
  • 30

1 Answers1

2

networkx has a method called relabel_nodes that takes a graph (G), a mapping (the relabeling rules) and returns a new graph (new_G) with the nodes relabeled.

That said, in your case:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_node('abc@gmail.com')
mapping = {
   'abc@gmail.com': 'abc'
}
relabeled_G = nx.relabel_nodes(G,mapping)
nx.draw(relabeled_G, with_labels=True)
plt.show()

That way you keep G intact and haves simplified labels.

You can optionally modify the labels in place, without having a new copy, in which case you'd simply call G = nx.relabel_nodes(G, mapping, copy=False)

If you don't know the email addresses beforehand, you can pass relabel_nodes a function, like so:

G = nx.relabel_nodes(G, lambda email: email.split("@")[0], copy=False)
Adelin
  • 7,809
  • 5
  • 37
  • 65
  • I just finished my code only find that nx.relabel_nodes replace all node name in .gexf file, it work just like G.add_node('abc') and '@gmail.com' disappears totally – Animeta Dec 13 '18 at 12:54