Creating a graph with images as nodes

心不动则不痛 提交于 2020-04-06 04:10:20

问题


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.

Any suggestions?


回答1:


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:

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


来源:https://stackoverflow.com/questions/53967392/creating-a-graph-with-images-as-nodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!