簡體   English   中英

網絡圖在 Python 中不顯示沿邊的箭頭

[英]Network graph not showing arrows along edge in Python

我有一個鄰接矩陣A 和一個定義每個節點坐標的數組:

import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
%matplotlib inline  

Import adjacency matrix A[i,j]
A = np.matrix([[0, 1, 1, 0, 0, 1, 0],
               [0, 0, 1, 1, 0, 0, 0],
               [0, 0, 0, 1, 1, 1, 0],
               [0, 0, 0, 0, 1, 1, 0],
               [0, 0, 0, 0, 0, 0, 1], 
               [0, 0, 0, 0, 0, 0, 1],
               [0, 0, 0, 0, 0, 0, 0]])

## Import node coordinates
xy = np.array([[0, 0],
               [-20, 20],
               [17, 27], 
               [-6, 49], 
               [15, 65], 
               [-20, 76],
               [5,  100]]) 

我的目標是繪制顯示節點如何相互連接的圖表。 因此,每條邊都應該有一個箭頭或雙向箭頭,指示沿着它前進的方向。

我能夠顯示連接,但沒有箭頭,即使我將參數指定為True

## Draw newtwork
G = nx.from_numpy_matrix(A, xy)
nx.draw_networkx(G, pos=xy, width=3, arrows=True)

您能否建議我一種在不修改輸入數據( Axy )的情況下實現目標的方法?

在此處輸入圖像描述

在某些時候,我對網絡x繪圖設施缺乏正確的箭頭支持感到非常惱火,並編寫了我自己的,同時保持API幾乎相同。 代碼可以在這里找到。

在此輸入圖像描述

import numpy as np
import netgraph

A = np.matrix([[0, 1, 1, 0, 0, 1, 0],
              [0, 0, 1, 1, 0, 0, 0],
              [0, 0, 0, 1, 1, 1, 0],
              [0, 0, 0, 0, 1, 1, 0],
              [0, 0, 0, 0, 0, 0, 1],
              [0, 0, 0, 0, 0, 0, 1],
              [0, 0, 0, 0, 0, 0, 0]])

xy = np.array([[0, 0],
               [-20, 20],
               [17, 27],
               [-6, 49],
               [15, 65],
               [-20, 76],
               [5,  100]])

N = len(A)
node_labels = dict(zip(range(N), range(N)))
netgraph.draw(np.array(A), xy / np.float(np.max(xy)), node_labels=node_labels)

我設法獲得了“箭頭”。 從挖掘其他堆棧溢出問題( 此處此處 )看來,這是使用matplotlib獲取箭頭的最佳方法。

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt


#Import adjacency matrix A[i,j]
A = np.matrix([[0, 1, 1, 0, 0, 1, 0],
               [0, 0, 1, 1, 0, 0, 0],
               [0, 0, 0, 1, 1, 1, 0],
               [0, 0, 0, 0, 1, 1, 0],
               [0, 0, 0, 0, 0, 0, 1], 
               [0, 0, 0, 0, 0, 0, 1],
               [0, 0, 0, 0, 0, 0, 0]])

## Import node coordinates
xy = np.array([[0, 0],
               [-20, 20],
               [17, 27], 
               [-6, 49], 
               [15, 65], 
               [-20, 76],
               [5,  100]]) 

G = nx.from_numpy_matrix(np.array(A), create_using = nx.MultiDiGraph())
pos = xy
nx.draw(G,pos)
labels = {i: i + 1 for i in G.nodes()}
nx.draw_networkx_labels(G, pos, labels, font_size=15, arrows=True)
plt.show()

產量

我遇到了類似的問題,即使在使用帶有箭頭參數的 draw.networkx 為 True 后我也沒有得到箭頭標記。

發現這是因為使用 pandas 創建的圖不是有向圖(箭頭只會顯示有向圖)

您可以使用下面的 function 檢查圖形是否為有向圖

nx.is_directed(G)

你可以按照下面的代碼片段從 pandas 創建二合字母

G = nx.from_pandas_edgelist(df, "source", "target", create_using=nx.DiGraph())

你可以使用nx.is_directed(G)檢查你的圖是否是有向的。 如果不是,請使用以下代碼來初始化有向圖。

 G=nx.DiGraph()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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