python - 在 Python 中生成具有并行标记边/顶点的有向图

标签 python graph currency directed-graph

在 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

最佳答案

您可以使用数据帧将边直接读入 NetworkX 图,使用 from_pandas_adjacency 。为此,我们将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与上面的工作示例。

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

引用文献:

关于python - 在 Python 中生成具有并行标记边/顶点的有向图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60262159/

相关文章:

javascript - toLocaleString 价格不带小数点零

python - 我怎样才能只将 1 个结果打印到控制台而不是两个?

python - 使用 torch 视觉创建火车变换时出错

database - 如何将图形数据存储在数据库中?

performance - Cypher:将 UNWIND 与可能为空的集合一起使用

swift - 如何从字符串中删除一些空格?

python - 增量湖增量 list 文件生成

python - coursera-dl osx 不是从命令行运行的

python - 按边缘属性进行深度优先搜索

AngularJS:货币格式。更改分数大小、千位分隔符和分数分隔符