Natasha
Natasha

Reputation: 1521

Creating a graph with images as nodes

I'm creating a graph with nodes as images,

# image from http://matplotlib.sourceforge.net/users/image_tutorial.html

I want to create a circular layout, with node zero positioned at the center.Egdelist is [(0,1),(0,2),(0,3),(0,4),(0,5)]

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import networkx as nx

img=mpimg.imread('stinkbug.png')
G=nx.complete_graph(6)
G.node[0]['image']=img
G.node[1]['image']=img
G.node[2]['image']=img
G.node[3]['image']=img
G.node[4]['image']=img
G.node[5]['image']=img
print(G.nodes())
G.add_edge(0,1)
G.add_edge(0,2)
G.add_edge(0,3)
G.add_edge(0,4)
G.add_edge(0,5)
print(G.edges())
nx.draw_circular(G)

But, in the output I find additional edges(snapshot attached).Is there a way to remove these additional edges? I want only these conncetions Egdelist is [(0,1),(0,2),(0,3),(0,4),(0,5)].Also, the original image is not displayed in the nodes. enter image description here

Any suggestions?

Upvotes: 6

Views: 10915

Answers (1)

Johannes Wachs
Johannes Wachs

Reputation: 1310

so there are really two questions in here. The first is why your graph has more edges than you want. This happened because you used nx.complete_graph(6) to initialize your graph - which creates a complete graph on 6 nodes. You should rather initialize an empty graph, add nodes with the image metadata, then add edges.

To have nodes drawn as your image, I found and slightly adapted code from this discussion. It has a few things you can customize, such as the image size. The result is:

enter image description here

Hope this helps!

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import networkx as nx

img=mpimg.imread('/Users/johanneswachs/Downloads/stink.jpeg')
G=nx.Graph()
G.add_node(0,image= img)
G.add_node(1,image= img)
G.add_node(2,image= img)
G.add_node(3,image= img)
G.add_node(4,image= img)
G.add_node(5,image= img)

print(G.nodes())
G.add_edge(0,1)
G.add_edge(0,2)
G.add_edge(0,3)
G.add_edge(0,4)
G.add_edge(0,5)
print(G.edges())
pos=nx.circular_layout(G)

fig=plt.figure(figsize=(5,5))
ax=plt.subplot(111)
ax.set_aspect('equal')
nx.draw_networkx_edges(G,pos,ax=ax)

plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)

trans=ax.transData.transform
trans2=fig.transFigure.inverted().transform

piesize=0.2 # this is the image size
p2=piesize/2.0
for n in G:
    xx,yy=trans(pos[n]) # figure coordinates
    xa,ya=trans2((xx,yy)) # axes coordinates
    a = plt.axes([xa-p2,ya-p2, piesize, piesize])
    a.set_aspect('equal')
    a.imshow(G.node[n]['image'])
    a.axis('off')
ax.axis('off')
plt.show()

Upvotes: 13

Related Questions