[英]Wrong networkx Graph and visulisations are ugly
我有一个由 60 多个(2x2)大小的值组成的数据框,一些数据的样本如下
label data_pairs
-1040 [(-1037.13, -1044.77)]
-1092 [(-1102.64, -1081.64)]
-1105 [(-1107.36, -1102.64)]
-137 [(-136.19, -138.75)]
-1431 [(-1434.08, -1429.31)]
-612 [(-622.47, -601.98)]
-672 [(-669.77, -674.95)]
-752 [(-748.22, -755.9)]
-791 [(-795.19, -788.02)]
正如数据集中的名称所暗示的那样,我想为该pair's values
绘制networkx
图并相应地label
它们。 根据 StackOverflow 用户建议之一,我按照他的指导进一步修改了代码如下
df=pd.read_excel (r'C:\Users\xxx\Documents\Python Scripts\Python
Scripts\uuu\data_pairs.xlsx') # type: datFrame (10,2)
networkx
代码如下
import networkx as nx
G = nx.DiGraph()
edges = np.stack(df.Pairs.to_numpy()).reshape(-1,2) # array of str1248 (5,2)
G = nx.from_edgelist(edges)
pos = nx.spring_layout(G, k=0.6) # dict
fig=plt.figure(figsize=(10,2),dpi=300)
nx.draw(G, pos=pos, node_size=800, with_labels=True,node_color='y')
edges
值看起来像这样
[(-1037.13, -1044.77)] [(-1102.64, -1081.64)]
[(-1107.36, -1102.64)] [(-1187.16, -1192.42)]
[(-1261.33, -1280.02)] [(-136.19, -131.06)]
[(-131.06, -138.75)] [(-136.19, -138.75)]
[(-1434.08, -1429.31)] [(-304.94, -308.8), (-304.94, -307.85)]
正如您所看到的,由于使用两个值来连接图形的edges
值,这些数字看起来是错误的。 此外,图中没有显示标签。 例如对于data_pairs
值 [(-1037.13, -1044.77)] 我应该在行之间得到label
值 -1040。 像这样的东西(-1037.13)--------------------> (-1044.77)
等等。
-1040
以上只是为了理解。
你能帮我如何得到这样的结果吗? 非常感谢提前
问题是您的列包含嵌套在列表中的元组。 你需要让正确结构的值networkX
构建rgaph预期。 一种简单的方法是将值堆叠到一个数组中,然后适当地重新整形。
此外, nx.spring_layout
有一个参数k
,用于设置图中节点之间的间距:
from ast import literal_eval
from itertools import chain
df['data_pairs']= df['data_pairs'].map(literal_eval)
G = nx.from_edgelist(chain.from_iterable(df.data_pairs))
plt.figure(figsize=(10,5))
pos = nx.spring_layout(G, k=.6)
nx.draw(G,
pos=pos,
node_size=800,
with_labels=True,
node_color='y')
输入数据 -
G.edges()
EdgeView([(-1037.13, -1044.77), (-1102.64, -1081.64), (-1102.64, -1107.36),
(-136.19, -138.75), (-1434.08, -1429.31), (-622.47, -601.98),
(-669.77, -674.95), (-748.22, -755.9), (-795.19, -788.02),
(-304.94, -308.8), (-304.94, -307.85)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.