我想要可视化一个具有节点和边缘的社交网络,节点的颜色表示属性的值。如果我可以使用python中的工具(比如网络)来做这件事,那就太好了,但我也对其他工具(如伤寒、图形工具)开放。我在社交网络中拥有的节点和边缘是以numpy数组的形式出现的。我希望根据属性值对这个可视化的节点进行着色。
节点数组中的每一行指向一个用户。节点数组中的每个列指向一个属性。节点数组每列中的值指向属性值。下面是一个具有10个用户和3个属性(名称为Att1
、Att2
、Att3
)的节点数组的示例。
Nodes = np.array([[1,2,4],[1,3,1],[2,2,1],[1,1,2],
[1,2,2],[2,1,4],[1,2,1],[2,0,1],
[2,2,4],[1,0,4]])
类似地,边数组(邻接矩阵)是节点大小数的平方数组,*
节点数。邻接矩阵中的值1表示两个节点之间存在边,值0表示没有边。下面是一个边缘数组的示例。
Edges = np.random.randint(2, size=(10,10))
假设我希望根据Nodes
的中间列中给出的属性值对节点进行着色(即Attribute_Value = Nodes[:,1] = [2, 3, 2, 1, 2, 1, 2, 0, 2, 0])
有四个唯一的属性值[0,1,2,3]
),因此,我希望为这些节点有四种不同的颜色。在我的实际图表中,我有许多属性的唯一值。此外,我有数以万计的节点,所以我希望能够调整我的地块中节点的大小(半径)。
在我之前发表过一篇文章之后,我尝试过这样做:
import networkx as nx
G = nx.from_numpy_array(Edges)
nx.draw(G, with_labels=True)
但是,上述代码片段的结果不允许我根据属性值选择颜色。此外,我需要调整节点的大小。我如何以描述的方式可视化社会图表?
发布于 2019-01-10 10:42:22
networkx.draw
接受node_color
和node_size
的列表,这些列表需要与节点数一样长。因此,您只需将您独特的属性映射到某些颜色,并创建这些列表。如果您有许多不同的属性,您将需要自动地进行映射。下面,我概述了两个选项,一个使用matplotlib颜色周期,另一个简单地为唯一属性分配随机颜色。
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
Nodes = np.array([[1,2,4],
[1,3,1],
[2,2,1],
[1,1,2],
[1,2,2],
[2,1,4],
[1,2,1],
[2,0,1],
[2,2,4],
[1,0,4]])
Edges = np.random.randint(2, size=(10,10))
attribute_values = Nodes[:,1]
# make a color mapping from node attribute to color
# option 1: using the matplotlib color cycle;
# however, you may run out of colors if there are many different unique attributes
color_cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
attribute_to_color = dict()
for ii, attribute in enumerate(np.unique(attribute_values)):
attribute_to_color[attribute] = color_cycle[ii]
# option 2: assign random colors
attribute_to_color = dict()
for ii, attribute in enumerate(np.unique(attribute_values)):
attribute_to_color[attribute] = np.random.rand(3)
node_color = [attribute_to_color[attribute] for attribute in attribute_values]
# adjust node sizes according to some other attribute
node_size = Nodes[:, 2] * 100
G = nx.from_numpy_matrix(Edges)
nx.draw(G, node_color=node_color, node_size=node_size, with_labels=True)
plt.show()
发布于 2019-01-10 10:43:52
Networkx允许可视化图形并指定节点的大小和颜色。例如:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.barabasi_albert_graph(20, 2)
node_colors = [x for x in range(20)]
node_sizes = [50 * x for x in range(20)]
cmap = plt.cm.jet
nx.draw_networkx(G,
with_labels=True,
labels={node : 'some text {}'.format(node) for node in G.nodes()},
node_color=node_colors,
node_size=node_sizes,
cmap=cmap)
plt.show()
其结果是:
为了充分理解Networkx绘图的工作原理,我建议阅读文档。
就个人而言,为了探索和可视化特定于的图形实例,我更喜欢将networkx图保存到文件中,并使用gephi加载它。如果您希望对许多图形实例进行自动化处理,则网络be可能会更好。
如果您选择GUI,只需加载一个图形并使用GUI,这是相当不言自明的。
https://stackoverflow.com/questions/54119289
复制相似问题