简体   繁体   English

Networkx 图和标签

[英]Networkx graph and labels

I am having some troubles to understand how networkx library works & nodes' labels.我在理解 networkx 库的工作原理和节点标签方面遇到了一些麻烦。 Let's assume I have a correlation matrix in a pandas dataframe:假设我在 pandas dataframe 中有一个相关矩阵:

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

D = pd.DataFrame\
({'A': [1, 0.5, 0.1], 'B': [0.5, 1, 0.3], 'C': [0.1, 0.3, 1]}, index =  ['A', 'B', 'C'])

I now would like to plot the simple graph representation of this correlation matrix (so a triangle in this example), and then generate the minimum spanning tree for bigger correlation matrices/distance matrices.我现在想 plot 这个相关矩阵的简单图形表示(在这个例子中是一个三角形),然后为更大的相关矩阵/距离矩阵生成最小生成树。

corr_graph = nx.from_pandas_adjacency(D)
pos = nx.spring_layout(corr_graph)
nx.draw_networkx_nodes(corr_graph ,pos=pos, label = ['A', 'B', 'C'])
nx.draw_networkx_edges(corr_graph ,pos=pos)
nx.draw_networkx_edge_labels(corr_graph , pos=pos)
plt.axis('off')
plt.show()

So the graph is generated, with correct labels on each edges.因此生成了图形,每个边上都有正确的标签。 On the nodes I have the self-loop edges {'weight':1} but the nodes themselves have no labels and I wanted to have them as A, B and C as in my initial dataframe so I can identify them.在节点上,我有自循环边{'weight':1}但节点本身没有标签,我希望它们为 A、B 和 C,就像我最初的 dataframe 一样,这样我就可以识别它们。 My other question is how to remove the self-loop edges labels.我的另一个问题是如何删除自循环边缘标签。

I'd like to do the same with the minimum spanning tree but first I am just trying to do it on the simple graph.我想对最小生成树做同样的事情,但首先我只是想在简单的图表上做。

Thank you,谢谢,

Drawing node labels绘图节点标签

(in-built function): (内置功能):

nx.draw_networkx_labels(corr_graph, pos=pos)

Removing self loops:删除自循环:

method 1:方法一:

set the diagonal to zero, and then create the graph:将对角线设置为零,然后创建图形:

# for example
E = D - np.eye(D.shape[0])
corr_graph = nx.from_pandas_adjacency(E)

method 2:方法二:

create graph, and only draw edges that have different source and dest.创建图形,并且只绘制具有不同源和目标的边。

corr_graph = nx.from_pandas_adjacency(D)
edges = [(a,b) for (a,b) in corr_graph.edges() if a != b]
nx.draw_networkx_edges(corr_graph, edgelist=edges, pos=pos)

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

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