在Python中生成带有平行标记的边/顶点的有向图

问题描述 投票:1回答:1

[用下面的图像在Python中生成带有平行标记的边/顶点的有向图的最佳方法是什么?

我已经尝试过networkx,但是它不适用于平行边缘。

enter image description here

这是我用来为图形生成数据的代码。

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
python graph currency directed-graph
1个回答
1
投票

您可以使用数据框使用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()

Currency Graph

注意:箭头附近的数字是边缘粗细。

您也可以通过上述工作示例查看this Google Colab Notebook

您可以根据需要调整字体大小,标签位置等。

参考:

© www.soinside.com 2019 - 2024. All rights reserved.