使用图像作为节点创建图形。

5

我正在创建一个以图像为节点的图表,

# 图像来源于http://matplotlib.sourceforge.net/users/image_tutorial.html

我想创建一个圆形布局,其中节点zero位于中心位置。Egdelist 是 [(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)]。另外,原始图像在节点中没有显示。
任何建议吗?
1个回答

12

在这里有两个问题。第一个是为什么你的图形具有比你想要的更多的边缘。这是因为你使用了nx.complete_graph(6)来初始化你的图形 - 这创建了一个完整的6节点图。相反,你应该初始化一个空图,使用图像元数据添加节点,然后添加边缘。

为了让节点绘制成你的图像,我从这个讨论中找到并稍微调整了一下代码。它有几个你可以自定义的东西,比如图像大小。结果是:

enter image description here

希望这可以帮助你!

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

1
请问您能解释一下这两行代码吗?trans=ax.transData.transform trans2=fig.transFigure.inverted().transform - Natasha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接