在 Python 中使用 networkX 将节点标签替换为表情符号

Substitute node labels with emoji using networkX in Python

我正在使用 networkX 从距离矩阵(emoji_sim、DataFrame)绘制网络图。这是代码:

G = nx.from_numpy_matrix(np.array(emoji_sim))
nx.draw(G, edge_color='silver', node_color='lightsalmon', with_labels=True)
plt.show()

我知道有一种方法可以将节点重新标记为:

G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())), range(1, len(G.nodes())+1))))   

但我想用图像替换节点标签(可能从文件中读取或使用 Python 表情符号包)。有什么办法吗?非常感谢!

澄清一下,我正在尝试用图片替换实际的圆圈。

它背后的想法不是很困难,但为了让它显示(至​​少在 ubunto 上)它让我遇到了一些困难,因为并非所有字体都支持表情符号。我将展示直接的方式,然后是一些最终对我有帮助的链接(也许你不需要那些)。

从表情符号 cheat sheet from the emoji python package 我选了三个作为示例,这是代码。

G = nx.Graph()
G.add_nodes_from([0,1,2])
n0 = emoji.emojize(':thumbsup:',use_aliases=True)
n1 = emoji.emojize(':sob:',use_aliases=True)
n2 = emoji.emojize(':joy:',use_aliases=True)
labels ={0:n0,1:n1,2:n2}
nx.draw_networkx(G,labels=labels, node_color = 'w', linewidths=0, with_labels=True, font_family = 'Symbola' ,font_size = 35)    
plt.show()

遇到的困难:

1- My machine is on ubunto 14.04, I could not display any emoji they always appeared as rectangles

使用以下命令安装了所需的字体 Symbola (mentioned here):

sudo apt-get install ttf-ancient-fonts

2- Maplotlib (which networkx calls to draw) is not using the installed font.

从几个有用的讨论中 1 2 3 4 5 6 我将 Symbola 的 .tff 字体文件复制并粘贴到默认的 matplotib 目录中(它在其中获取要使用的字体)。

cp /usr/share/fonts/truetype/ttf-ancient-scripts/Symbola605.ttf /usr/share/matplotlib/mpl-data/fonts/ttf

然后我不得不删除 fontList.cache 文件以加载新字体。

rm ~/.cache/matplotlib/fontList.cache

备注

您可以通过更改 draw_networkx 的输入来获得不同的视图,例如不发送 linewidths 将显示每个节点的圆形边框,如果您想要节点的特定背景颜色,请将 color_node 从白色更改为您想要的颜色...有关更多详细信息,请检查 documentation.