python表情换头,在Python中使用networkX用表情符号替换节点标签

I am using networkX to draw a network plot from a distance matrix(emoji_sim, a DataFrame). Here is the code:

G = nx.from_numpy_matrix(np.array(emoji_sim))

nx.draw(G, edge_color='silver', node_color='lightsalmon', with_labels=True)

plt.show()

I know there is a way to relabel the nodes as:

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

But I want to substitute the nodes label with images(possibly read from files or using Python Emoji package). Is there any way to do that? Thanks a lot!

To clarify, I am trying to substitute the actual circle with images.

解决方案

The idea behind it is not very difficult but in order to get it to be displayed (at least on ubunto) it gave me some hard time as not all fonts support emoji. I shall display the straight forward way then some links that helped me in the end (maybe you will not need those).

From emoji cheat sheet from the emoji python package I picked up three to be shown as an example and here is the code.

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()

2ebf0d92bb4cd74dea3f9b21ace59b1f.png

Difficulties encountered:

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

Installed needed font Symbola using the following command (mentioned here):

sudo apt-get install ttf-ancient-fonts

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

From several useful discussions 1 2 3 4 5 6 I copied and pasted the .tff font file of Symbola in the default matplotib directory (where it fetches for fonts to use).

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

Then I had to delete fontList.cache file for the new font to be loaded.

rm ~/.cache/matplotlib/fontList.cache

Note

You can have different views by changing the input to the draw_networkx e.g. not sending the linewidths will show circular border for each node, also if you want a specific background color for nodes change the color_node from white to a color that you want ... for more details check the documentation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值