Skip to content

Instantly share code, notes, and snippets.

@shobhit
Created August 2, 2012 11:21
Show Gist options
  • Save shobhit/3236373 to your computer and use it in GitHub Desktop.
Save shobhit/3236373 to your computer and use it in GitHub Desktop.
Put Images as Nodes using Networkx and Python
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('/home/shobhit/Desktop/shobhit.jpg')
# draw graph without images
G =nx.Graph()
G.add_edge(0,1,image=img,size=0.1)
G.add_edge(1,2,image=img,size=0.05)
G.add_edge(2,3,image=img,size=0.02)
G.add_edge(3,4,image=img,size=0.075)
pos=nx.spring_layout(G)
nx.draw(G,pos)
# add images on edges
ax=plt.gca()
fig=plt.gcf()
label_pos = 0.5 # middle of edge, halfway between nodes
trans = ax.transData.transform
trans2 = fig.transFigure.inverted().transform
imsize = 0.1 # this is the image size
for (n1,n2) in G.edges():
(x1,y1) = pos[n1]
(x2,y2) = pos[n2]
(x,y) = (x1 * label_pos + x2 * (1.0 - label_pos),
y1 * label_pos + y2 * (1.0 - label_pos))
xx,yy = trans((x,y)) # figure coordinates
xa,ya = trans2((xx,yy)) # axes coordinates
imsize = G[n1][n2]['size']
img = G[n1][n2]['image']
a = plt.axes([xa-imsize/2.0,ya-imsize/2.0, imsize, imsize ])
a.imshow(img)
a.set_aspect('equal')
a.axis('off')
plt.savefig('/home/shobhit/Desktop/save.png')
@munthe
Copy link

munthe commented May 23, 2019

Nice explanation. Can you please explain how can we add images at the nodes? I tried G.add_node(0, image = img, size = 0.2), but it doesn't work. Thanks in advance.

Changed it here to put images on the nodes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment