Python에서 레이블이 지정된 병렬 모서리/꼭짓점을 사용하여 방향 그래프 생성 (Generating Directed Graph With Parallel Labelled Edges/Vertices in Python)


문제 설명

Python에서 레이블이 지정된 병렬 모서리/꼭짓점을 사용하여 방향 그래프 생성 (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

참조 솔루션

방법 1:

You can use the dataframe to read the edges directly into a NetworkX graph using from_pandas_adjacency. In order to do that, lets set the index of the dataframe equal to chosen_currencies, to ensure that the edges are mapped correctly.

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

Now set the index

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

Now let's create the graph

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

Note: The number near the arrowhead is the edge weight.

You can also view this Google Colab Notebook with above working example.

You can adjust the font size, label position, etc. according to your requirements.

References:

(by Matheus TorquatoGambit1614)

참조 문서

  1. Generating Directed Graph With Parallel Labelled Edges/Vertices in Python (CC BY‑SA 2.5/3.0/4.0)

#directed-graph #Python #graph #currency






관련 질문

다른 유형의 멤버가 있는 두 개의 구조체를 선언하는 방법은 무엇입니까? (How to declare two structs which have members of the others type?)

깊이 우선 그래프 검색 트리의 백 에지 (Back Edges in a depth first graph search tree)

각 노드에 최대 하나의 아웃바운드 에지가 있는 완전 연결 방향 그래프를 무엇이라고 합니까? (What do you call a fully connected directed graph where each node has at most one outbound edge?)

Floyd-Warshall 알고리즘 (Floyd-Warshall algorithm)

도트 그래픽의 일부 라인을 평행하게 만드는 방법은 무엇입니까? (How to make some lines of a dot graphic parallel?)

그래프 구현에서 모든 주기 찾기 (Find all cycles in a graph implementation)

반전이 있는 TSP (TSP with a twist)

C++ 방향 그래프 깊이 우선 탐색 (c++ directed graph depth first search)

Python에서 레이블이 지정된 병렬 모서리/꼭짓점을 사용하여 방향 그래프 생성 (Generating Directed Graph With Parallel Labelled Edges/Vertices in Python)

개체 배열을 설정하는 동안 FindBug 오류 '변경 가능한 개체에 대한 참조를 통합하여 내부 표현을 노출할 수 있음'을 수정하는 방법은 무엇입니까? (How to Fix FindBug error 'May expose internal representation by incorporating reference to mutable object' while setting Array of Objects?)

그래프 직렬화 (Graph serialization)

유향 그래프를 저장/액세스하는 가장 좋은 방법 (Best Way to Store/Access a Directed Graph)







코멘트