Skip to content

Instantly share code, notes, and snippets.

@munthe
Forked from shobhit/nwxpython.py
Last active April 3, 2024 00:35
Show Gist options
  • Save munthe/7de513dc886917860f7b960a51c95e10 to your computer and use it in GitHub Desktop.
Save munthe/7de513dc886917860f7b960a51c95e10 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
import glob
from numpy import sqrt
import glob
path = ''
files = [f for f in glob.glob(path + "*.jpg")]
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.savefig('./save.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment