日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

圖鄰接矩陣可視化解析_python

作者:科技論文精講 ? 更新時(shí)間: 2023-01-15 編程語(yǔ)言

使用工具

#導(dǎo)入模塊
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse as sp

準(zhǔn)備數(shù)據(jù)

# 鄰接矩陣
Matrix = np.array(
    [
        [0, 1, 1, 1, 1, 1, 0, 0],  # a
        [0, 0, 1, 0, 1, 0, 0, 0],  # b
        [0, 0, 0, 1, 0, 0, 0, 0],  # c
        [0, 0, 0, 0, 1, 0, 0, 0],  # d
        [0, 0, 0, 0, 0, 1, 0, 0],  # e
        [0, 0, 1, 0, 0, 0, 1, 1],  # f
        [0, 0, 0, 0, 0, 1, 0, 1],  # g
        [0, 0, 0, 0, 0, 1, 1, 0]  # h
    ]
)

轉(zhuǎn)化臨界矩陣

def get_matrix_triad(coo_matrix , data=False):
	'''
		獲取矩陣的元組表示  (row,col)
		data 為 True 時(shí) (row,col,data)
	:dependent  scipy
	:param coo_matrix: 三元組表示的稀疏矩陣  類型可以為 numpy.ndarray
	:param data: 是否需要 data值
	:return:
		list
	'''
	# 檢查類型
	if not sp.isspmatrix_coo(coo_matrix):
		# 轉(zhuǎn)化為三元組表示的稀疏矩陣
		coo_matrix = sp.coo_matrix(coo_matrix)
	# nx3的矩陣  列分別為 矩陣行,矩陣列及對(duì)應(yīng)的矩陣值
	temp = np.vstack((coo_matrix.row , coo_matrix.col , coo_matrix.data)).transpose()
	return temp.tolist()

測(cè)試

edags = get_matrix_triad(Matrix)
-->
[[0.0, 0.0, 1.0],
 [0.0, 1.0, 1.0],
 [0.0, 2.0, 1.0],
 [0.0, 3.0, 1.0],
 [0.0, 4.0, 1.0],
 [0.0, 5.0, 1.0],
 [1.0, 1.0, 1.0],
 [1.0, 2.0, 1.0],
 [1.0, 4.0, 1.0],
 [2.0, 2.0, 1.0],
 [2.0, 3.0, 1.0],
 [3.0, 3.0, 1.0],
 [3.0, 4.0, 1.0],
 [4.0, 4.0, 1.0],
 [4.0, 5.0, 1.0],
 [5.0, 2.0, 1.0],
 [5.0, 5.0, 1.0],
 [5.0, 6.0, 1.0],
 [5.0, 7.0, 1.0],
 [6.0, 5.0, 1.0],
 [6.0, 6.0, 1.0],
 [6.0, 7.0, 1.0],
 [7.0, 5.0, 1.0],
 [7.0, 6.0, 1.0],
 [7.0, 7.0, 1.0]]

創(chuàng)建圖

# 創(chuàng)建一個(gè)沒有邊,沒有節(jié)點(diǎn)的空?qǐng)DGraph
G = nx.Graph()

添加節(jié)點(diǎn)

按照節(jié)點(diǎn)的個(gè)數(shù)添加節(jié)點(diǎn)

H = nx.path_graph(Matrix.shape[0]) 
G.add_nodes_from(H)

添加邊

G.add_edges_from(edags) #添加邊
# 若數(shù)據(jù)含有權(quán)重,及 get_matrix_triad() 中 data = True ,則使用
G.add_weighted_edges_from(edags)

繪圖

colors = np.arange(Matrix.shape[0])
nx.draw(G,pos=nx.spring_layout(G),node_color=colors)
plt.show()

效果圖

擴(kuò)展

美化圖

合理使用**draw_networkx ()**中的參數(shù),來(lái)美化圖

draw_networkx() 

https://networkx.github.io/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html#networkx.drawing.nx_pylab.draw_networkx

總結(jié)

原文鏈接:https://blog.csdn.net/yf289178199/article/details/90238328

欄目分類
最近更新