简体   繁体   English

如何从python中的networkx对象创建加权2D数组

[英]how to create weighted 2D array from networkx object in python

I'm completely new to Python (and programming in general). 我是Python(和一般编程)的新手。 A program I'm using has generated a gpickle file, the contents of which I would like to visualize in a 2D array. 我正在使用的程序已经生成了一个斑点文件,我想在2D数组中可视化该文件的内容。

This is what I've done so far: 到目前为止,这是我所做的:

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

P = np.load('/pathtoobject.gpickle')

This results in this line of text: 结果是这一行文本:

networkx.classes.graph.Graph object at 0x1d217d0

I've been able to create an undirected graph using... 我已经能够使用...创建无向图

nx.draw(P)
plt.show()

...but I would like to create a weighted 2D array, if possible. ...但如果可能的话,我想创建一个加权2D数组。 I do know that the object has 83x83 points. 我知道该对象具有83x83点。

You might try converting the networkx graph into a "dictionary of dictionaries" using networkx.convert.to_dict_of_dicts , or a SciPy adjacency matrix . 您可以尝试使用networkx.convert.to_dict_of_dictsSciPy邻接矩阵将networkx图转换为“字典词典”。 Then you could use something like matplotlib's matshow() to visualize it. 然后,您可以使用matplotlib的matshow()类的东西matshow()进行可视化。

Given a graph such as G : 给定一个图,例如G

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

np.random.seed(2014)
A = np.random.randn(83, 83)
G = nx.from_numpy_matrix(A)

you could use nx.to_numpy_matrix to obtain the graph's adjacency matrix. 您可以使用nx.to_numpy_matrix来获取图的邻接矩阵。 As ASGM suggested, you could then plot the "heatmap" using plt.matshow : 正如ASGM所建议的,您可以使用plt.matshow绘制“热图”:

B = nx.to_numpy_matrix(G)
plt.matshow(B)
plt.colorbar()
plt.show()

yields 产量 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM