Warm tip: This article is reproduced from stackoverflow.com, please click
python python-3.x networkx

How to display image icons on nodes in NetworkX

发布于 2020-03-27 10:30:05

I am using NetworkX module to present the network of an infrastructure systems. In this systems, nodes and edges consist of different types of entities and I would like to use some icons representing their types instead of circle, star or square.

G = nx.Graph()
G.add_edge('a', 'b')
nx.draw(G, labels={'a':'img1', 'b':'img2'}, with_labels=True)
plt.show()

Obviously, my script creates a graph with labels of 'img1' and 'img2'. I am looking for a way to display two icons instead of the filled circles and labels.

Questioner
a_g
Viewed
37
Joe 2019-07-04 01:07

You can create a plot using networkx and get the handle to the figure. Then use matplotlib to plot ontop of it.

import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
from numpy import sqrt
import glob

path = 'some/folder/with/png/files'
files = [f for f in glob.glob(path + "*.png")]
img = []
for f in files:
    img.append(mpimg.imread(f))
N = len(files)

# generate graph
G = nx.watts_strogatz_graph(N,4,0.2)
pos=nx.spring_layout(G,k=3/sqrt(N))

# draw with images on nodes
nx.draw_networkx(G,pos,width=3,edge_color="r",alpha=0.6)
ax=plt.gca()
fig=plt.gcf()
trans = ax.transData.transform
trans2 = fig.transFigure.inverted().transform
imsize = 0.1 # this is the image size
for n in G.nodes():
    (x,y) = pos[n]
    xx,yy = trans((x,y)) # figure coordinates
    xa,ya = trans2((xx,yy)) # axes coordinates
    a = plt.axes([xa-imsize/2.0,ya-imsize/2.0, imsize, imsize ])
    a.imshow(img[n])
    a.set_aspect('equal')
    a.axis('off')
plt.show()

Found at https://gist.github.com/munthe/7de513dc886917860f7b960a51c95e10

Here is an example that seems to plot on the edges instead of the nodes.