简体   繁体   中英

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

I'm completely new to Python (and programming in general). A program I'm using has generated a gpickle file, the contents of which I would like to visualize in a 2D array.

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. I do know that the object has 83x83 points.

You might try converting the networkx graph into a "dictionary of dictionaries" using networkx.convert.to_dict_of_dicts , or a SciPy adjacency matrix . Then you could use something like matplotlib's matshow() to visualize it.

Given a graph such as 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. As ASGM suggested, you could then plot the "heatmap" using plt.matshow :

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

yields 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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