簡體   English   中英

從pandas數據幀在python中的NetworkX中創建無向圖

[英]Create undirected graph in NetworkX in python from pandas dataframe

我是 Python 中 NetworkX 包的新手。 我想解決以下問題。

可以說這是我的數據集:

import pandas as pd 
d = {'label': [1, 2, 3, 4, 5], 'size': [10, 8, 6, 4, 2], 'dist': [0, 2, -2, 4, -4]}
df = pd.DataFrame(data=d)
df 

df 中的標簽和大小是不言自明的。 dist 列測量從最大標簽(標簽 1)到其余標簽的距離。 因此,在標簽 1 的情況下 dist 為 0。

我想制作類似於下圖的東西: 在此處輸入圖片說明

尺寸最大的標簽位於中心位置 (1abel 1)。 邊是從標簽 1 到所有其他標簽的距離,節點的大小與每個標簽的大小成正比。 是否可以?

非常感謝您提前。 如果問題不清楚,請告訴我。

import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
for _, row in df.iterrows():
    G.add_node(row['label'], pos=(row['dist'], 0), size=row['size'])
biggest_node = 1
for node in G.nodes:
    if node != biggest_node:
        G.add_edge(biggest_node, node)

nx.draw(G,
        pos={node: attrs['pos'] for node, attrs in G.nodes.items()},
        node_size=[node['size'] * 100 for node in G.nodes.values()],
        with_labels=True
        )
plt.show()

哪些情節

在此處輸入圖片說明

筆記:

您會注意到 1-3 和 1-2 中的邊緣更厚,因為它們分別與 1-5 和 1-4 的邊緣部分重疊。 您可以通過在每個方向上從中心到最遠節點只有一條邊來解決這個問題,因為每個節點都在同一條線上,所以它看起來是一樣的。

coords = [(attrs['pos'][0], node) for node, attrs in G.nodes.items()]
nx.draw(G,
        # same arguments as before and also add
        edgelist=[(biggest_node, min(coords)[1]), (biggest_node, max(coords)[1])]
        )

node_size參數列表中的 100 因子只是一個比例因子。 您可以將其更改為您想要的任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM