问题描述
我正在创建一个以节点为图像的图形,
I'm creating a graph with nodes as images,
#图片来自 http://matplotlib.sourceforge.net/users/image_tutorial .html
我想创建一个圆形布局,将节点zero
置于中心.egdelist为[[0,1),(0,2),(0,3),(0,4),(0 ,5)]
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)
但是,在输出中我发现了额外的边缘(附有快照),是否有办法去除这些额外的边缘?我只希望这些条件Egdelist是[(0,1),(0,2),(0,3),(0,4),(0,5)].此外,原始图像未显示在节点中.
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.
有什么建议吗?
推荐答案
所以这里确实有两个问题.第一个是为什么图形的边比您想要的多.发生这种情况的原因是,您使用nx.complete_graph(6)
初始化了图形-在6个节点上创建了完整的图形.您应该初始化一个空图,添加带有图像元数据的节点,然后添加边缘.
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:
希望这会有所帮助!
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()
这篇关于创建以图像为节点的图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!