[英]Generating Directed Graph With Parallel Labelled Edges/Vertices in Python
在 Python 中生成具有平行標記邊/頂點的有向圖(如下圖所示)的最佳方法是什么?
我已經嘗試過 networkx 但它不適用於平行邊。
這是我用來生成圖表數據的代碼。
from forex_python.converter import CurrencyRates
import pandas as pd
chosen_currencies = ['GBP', 'EUR', 'USD']
c = CurrencyRates()
rates = []
for currency_index in range(len(chosen_currencies)):
temp_list = []
for second_index in range(len(chosen_currencies)):
temp_list.append(c.get_rate(chosen_currencies[currency_index], chosen_currencies[second_index]))
rates.append(temp_list)
df = (pd.DataFrame.from_records(rates)).transpose()
df.columns = chosen_currencies
您可以使用數據框使用from_pandas_adjacency將邊直接讀入 NetworkX 圖中。 為了做到這一點,讓我們將dataframe
的索引設置為chosen_currencies
,以確保正確映射邊緣。
from forex_python.converter import CurrencyRates
import pandas as pd
chosen_currencies = ['GBP', 'EUR', 'USD']
c = CurrencyRates()
rates = []
for currency_index in range(len(chosen_currencies)):
temp_list = []
for second_index in range(len(chosen_currencies)):
temp_list.append(c.get_rate(chosen_currencies[currency_index], chosen_currencies[second_index]))
rates.append(temp_list)
df = (pd.DataFrame.from_records(rates)).transpose()
df.columns = chosen_currencies
# GBP EUR USD
#0 1.000000 0.83238 0.768233
#1 1.201374 1.00000 0.922935
#2 1.301689 1.08350 1.000000
現在設置索引
df.set_index([pd.Index(chosen_currencies)], inplace=True)
# GBP EUR USD
#GBP 1.000000 0.83238 0.768233
#EUR 1.201374 1.00000 0.922935
#USD 1.301689 1.08350 1.000000
現在讓我們創建圖表
import networkx as nx
import matplotlib.pyplot as plt
G = nx.from_pandas_adjacency(df, create_using=nx.DiGraph)
# Set the figure size
plt.figure(figsize=(8,8))
# Get the edge labels and round them to 3 decimal places
# for more clarity while drawing
edge_labels = dict([((u,v), round(d['weight'], 3))
for u,v,d in G.edges(data=True)])
# Get the layout
pos = nx.spring_layout(G)
# Draw edge labels and graph
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels,
label_pos=0.15, font_size=10)
nx.draw(G, pos, with_labels=True,
connectionstyle='arc3, rad = 0.15',
node_size=800)
plt.show()
注意:箭頭附近的數字是邊緣權重。
您還可以使用上述工作示例查看此 Google Colab Notebook 。
您可以根據自己的要求調整字體大小、標簽位置等。
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.