如何解决我无法基于三个条件与networkx形成图
我是Python的新手。请帮助我解决图形构造问题。我有一个属性为“源”,“对话者”和“频率”的数据库。
三行示例:
我需要基于Source-Interlocutor构建一个图形,但是还要考虑频率。
赞:
我的代码:
dic_values={Source:[24120.0,24120.0,24120.0],Interlocutor:[34,34,34],Frequency:[446625000,442475000,445300000]
session_graph=pd.DataFrame(dic_values)
friquency=session_graph['Frequency'].unique()
plt.figure(figsize=(10,10))
for i in range(len(friquency)):
df_friq=session_subset[session_subset['Frequency']==friquency[i]]
G_frique=nx.from_pandas_edgelist(df_friq,source='Source',target='Interlocutor')
pos = nx.spring_layout(G_frique)
nx.draw_networkx_nodes(G_frique,pos,cmap=plt.get_cmap('jet'),node_size = 20)
nx.draw_networkx_edges(G_frique,arrows=True)
nx.draw_networkx_labels(G_frique,pos)
plt.show()
我这样子:
解决方法
您的问题需要一个MultiGraph
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
import pydot
from IPython.display import Image
dic_values = {"Source":[24120.0,24120.0,24120.0],"Interlocutor":[34,34,34],"Frequency":[446625000,442475000,445300000]}
session_graph = pd.DataFrame(dic_values)
sources = session_graph['Source'].unique()
targets = session_graph['Interlocutor'].unique()
#create a Multigraph and add the unique nodes
G = nx.MultiDiGraph()
for n in [sources,targets]:
G.add_node(n[0])
#Add edges,multiple connections between the same set of nodes okay.
# Handled by enum in Multigraph
#Itertuples() is a faster way to iterate through a Pandas dataframe. Adding one edge per row
for row in session_graph.itertuples():
#print(row[1],row[2],row[3])
G.add_edge(row[1],label=row[3])
#Now,render it to a file...
p=nx.drawing.nx_pydot.to_pydot(G)
p.write_png('multi.png')
Image(filename='multi.png') #optional
这将产生以下内容:
请注意,使用Graphviz / Pydot时,节点布局会比较棘手。 例如,检查this SO answer.。希望这可以帮助您前进。欢迎来到。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。