[英]Position of images as nodes in networkx plot?
使用此答案生成以图像为节点的 plot 后,我在使节点的 y 坐标位置与图像的 y 坐标位置对齐时遇到了一些困难:
节点的x,y
位置设置为:
pos={
0: [0, 0],
1: [1, 0],
2: [2, 0],
3: [3, 0],
4: [4, 0],
5: [5, 0],
6: [6, 0],
7: [5, 1]
}
生成 plot 的代码是:
pos:Dict={}
for nodename in G.nodes:
pos[nodename]=G.nodes[nodename]["pos"]
print(f'pos={pos}')
fig=plt.figure(figsize=(1,1))
ax=plt.subplot(111)
ax.set_aspect('equal')
nx.draw_networkx_edges(G,pos,ax=ax)
# plt.xlim(-1,10)
# plt.ylim(-1.5,1.5)
trans=ax.transData.transform
trans2=fig.transFigure.inverted().transform
piesize=0.3 # this is the image size
p2=piesize/2.0
for n in G:
xx,yy=trans(pos[n]) # figure coordinates
#print(f'xx,yy={xx,yy}')
xa,ya=trans2((xx,yy)) # axes coordinates
print(f'xa,ya={xa,ya}')
a = plt.axes([xa-p2,ya-p2, piesize, piesize])
a.set_aspect('equal')
a.imshow(G.nodes[n]['image'])
a.axis('off')
ax.axis('off')
plt.show()
但是,边缘的 y 坐标与图像的 y 坐标不对齐。 我预计这是因为应用于plt.axes[[xa-p2...
线的坐标变换未应用于边图。
我怎样才能确保图像被放置在它们的x,y
坐标位置上,一个大小为[x_min,x_max,y_min,y_max]
的图形,同时确保 .networkx Graph 的边缘也指向伴随坐标?
尽量不要将轴比率设置为相等(即删除此行ax.set_aspect('equal')
)。
虽然这有望解决问题,但可能还会出现其他问题,即箭头隐藏在图像后面。 一种解决方案是在调用nx.draw.networkx_edges()
时设置node_size
参数。
这样做的另一个挑战是,图像尺寸似乎具有不同的长度和高度值。 解决方法是首先使用较大的node_size
绘制垂直边缘。 然后添加水平边缘并设置较小的node_size
(垂直边缘将再次绘制,但它们的箭头隐藏在图像后面)。 您可能需要稍微调整一下这些值。
pos={
0: [0, 0],
1: [1, 0],
2: [2, 0],
3: [3, 0],
4: [4, 0],
5: [5, 0],
6: [6, 0],
7: [5, 1]
}
img=mpimg.imread(sample_img_path)
G=nx.DiGraph()
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)
G.add_node(6,image=img)
G.add_node(7,image=img)
fig=plt.figure(figsize=(12,3))
ax=plt.subplot(111)
#ax.set_aspect('equal') # <-- not set the aspect ratio to equal
# draw vertical edges using a larger node size
G.add_edge(4,7)
G.add_edge(5,7)
G.add_edge(6,7)
nx.draw_networkx_edges(G,pos,ax=ax, node_size=8000, arrowsize=30)
# add the horizontal edges with a smaller node size
G.add_edge(0,1)
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(3,4)
G.add_edge(4,5)
G.add_edge(6,5)
nx.draw_networkx_edges(G,pos,ax=ax, node_size=3000, arrowsize=30)
trans=ax.transData.transform
trans2=fig.transFigure.inverted().transform
piesize=0.4 # 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.nodes[n]['image'])
a.axis('off')
ax.axis('off')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.