0

私はネットワーク分析を学ぼうとしているので、ヒラリー・クリントンの電子メールをオンラインで使用して、誰が誰に電子メールを送信したかを確認しています。

私のデータは、hrc_dict という辞書にあります。送信者と受信者のタプルに続いて、電子メールの頻度があります。これは辞書の一部です:

{('ヒラリー・クリントン', 'シェリル・ミルズ'): 354, ('ヒラリー・クリントン', 'l'): 1, ('リンダ・デワン', 'ヒラリー・クリントン'): 1, ('ヒラリー・クリントン', 'カプリシアマーシャル'): 9, ('フィリップ・クロウリー', 'ヒラリー・クリントン'): 2, ('シェリル・ミルズ', 'アン・マリー・スローター'): 1}

Jupyter で Networkx を使用してグラフを作成しています。私のコードは以下の通りです:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()

G.add_nodes_from(hrc_dict)

for s, r in hrc_dict:
    G.add_edge((s,r), hrc_dict[(s,r)])

G.add_edge((s,r), hrc_dict[(s,r)])

nx.Graph() を呼び出しても何も出力されず、G.nodes() を呼び出してもすべてのノードが表示されません。出力の一部をここに貼り付けました。

[1, 2, 3, 4, 5, 6, 7, 8, 'マーク・ペン', 10, ('トッド・スターン', 'ヒラリー・クリントン'), 12,]

G.edges() を呼び出すと、次のようになります。

[(1, ('ヒラリー・クリントン', 'l')), (1, ('リンダ・ディーワン', 'ヒラリー・クリントン')), (1, ('ヒラリー・クリントン', 'トーマス・シャノン')), (1 , ('シェリル・ミルズ', 'アン・マリー・スローター')), (1, ('クリストファー・バッツギー', 'ヒラリー・クリントン'))]

グラフにノードを正しく追加する方法を知っている人はいますか? それぞれの人がノードである必要があると思いますが、タプルを分割して名前を個別に追加するにはどうすればよいでしょうか? エッジは正しく表示されていますか、それとも別の方法で入力する必要がありますか?

4

2 に答える 2

3

各人物をノードとして追加するには、 の使用も変更する必要がありますadd_nodes_from

このようなもの:

srcs, dests = zip(* [(fr, to) for (fr, to) in hrc_dict.keys()])
G.add_nodes_from(srcs+dests)

ノードのリストが次のようG.nodes()になることを意味します。

['Cheryl Mills',
 'Capricia Marshall',
 'Anne-Marie Slaughter',
 'Phillip Crowley',
 'Hillary Clinton',
 'l',
 'Linda Dewan']

(networkx はグラフを辞書として保存するため、重複はありません)。

注: エッジを追加するために以下の方法を使用する場合、最初にノードを追加する必要はありません。重要)、このコードはそれを行います。

次に、基本的にジョエルの答えに従ってエッジを追加します。ただし、属性「重み」の使用にも注意してください。これにより、レイアウトで情報を直接利用できます。

import networkx as nx
import matplotlib.pyplot as plt

hrc_dict = {('Hillary Clinton', 'Cheryl Mills'): 355, ('Hillary Clinton', 'l'): 1, ('Linda Dewan', 'Hillary Clinton'): 1, ('Hillary Clinton', 'Capricia Marshall'): 9, ('Phillip Crowley', 'Hillary Clinton'): 2, ('Cheryl Mills', 'Anne-Marie Slaughter'): 1}

G = nx.Graph()

# To add the a node for each of the email parties:
srcs, dests = zip(* [(fr, to) for (fr, to) in hrc_dict.keys()])
G.add_nodes_from(srcs + dests)
# (but it isn't needed IF the following method is used
#  to add the edges, since add_edge also creates the nodes if
#  they don't yet exist)

# note the use of the attribute "weight" here
for (s,r), count in hrc_dict.items():
    G.add_edge(s, r, weight=count)

# produce info to draw:
# a) if weight was used above, spring_layout takes 
#    into account the edge strengths
pos = nx.spring_layout(G)

# b) specifiy edge labels explicitly
# method from https://groups.google.com/forum/#!topic/networkx-discuss/hw3OVBF8orc
edge_labels=dict([((u,v,),d['weight'])
             for u,v,d in G.edges(data=True)])

# draw it
plt.figure(1);
nx.draw_networkx(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)

plt.axis('equal') # spring weighting makes more sense this way
plt.show()

そして、これは私たちが見るかもしれないものです:

出力例 - HC/A-MS エッジが非常に強いため、非常に短いことに注意してください。

于 2015-12-08T20:22:36.467 に答える