簡體   English   中英

Position 圖像作為節點 in.networkx plot?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM