简体   繁体   English

简化 networkx 节点标签

[英]Simplify networkx node labels

%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输出图是

在此处输入图像描述

What I want is我想要的是

在此处输入图像描述

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.我在 csv 文件中有数千条从 person@email.com 到 another@email.com 的电子邮件记录,我使用G.add_node(email_address)G.add_edge(from, to)构建 G。我想保留整个电子邮件Graph G 中的地址,但以简化的字符串显示。

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. networkx有一个名为relabel_nodes的方法,它接受一个图 ( G )、一个mapping (重新标记规则)并返回一个带有重新标记节点的新图 ( new_G )。

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.这样你就可以保持G的完整性并简化标签。

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)您可以选择就地修改标签,而无需新副本,在这种情况下,您只需调用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:如果您事先不知道电子邮件地址,可以将relabel_nodes传递给函数,如下所示:

G = nx.relabel_nodes(G, lambda email: email.split("@")[0], copy=False)
import networkx as nx
import matplotlib.pyplot as plt  

G = nx.Graph()
G.add_node('abc@gmail.com')

mapping = {'abc@gmail.com':'abc' }
G=nx.relabel_nodes(G, mapping)

nx.draw(G, with_labels=True)
plt.rcParams["figure.figsize"] = [10,10]
plt.axis('off')
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM