【问题标题】:networkx graph with csv input and plotly output带有 csv 输入和 plotly 输出的 networkx 图
【发布时间】:2020-02-19 22:12:59
【问题描述】:

一些背景...

我是 python 和 networkx 的初学者...

我有一个包含多列的 csv 文件。

我提取了包含发送者和接收者地址的列,并将它们放入列表中,如下所示:

with open('file.csv,'r') as csv_file:
    lines = csv_file.readlines()

sip = []
dip = []

for line in lines:
    data = line.split(',')
    sip.append(data[9])
    dip.append(data[10])
nodes=list(set().union(sip,dip))
edges=list(set().union(list(zip(sip,dip))))

快速打印我的 G.nodes() 和 G.edges() 给我以下输出:

edges = [('AddressA','AddressB'),('AddressA','AddressC')]
nodes = ['AddressA','AddressB','AddressC']

其中 edges = [('senderaddress','receiveraddress')]

我的目标

我希望使用 networkx 来绘制发送者和接收者之间的连接。

我使用这个page 作为参考。

这是我当前的代码:

import plotly.graph_objs as go
import networkx as nx
from plotly.subplots import make_subplots

#######CREATE NODES/EDGES#############
G=nx.Graph()
nodes=list(set().union(sip,dip))
edges=list(set().union(list(zip(sip,dip))))
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos = nx.get_node_attributes(G,'pos')

edge_trace = go.Scatter(
    x=[],
    y=[],
    line=dict(width=0.5,color='#888'),
    hoverinfo='none',
    mode='lines')

for edge in G.edges():
    x0, y0 = G.nodes[edge[0]]['pos']
    x1, y1 = G.nodes[edge[1]]['pos']
    edge_trace['x'] += tuple([x0, x1, None])
    edge_trace['y'] += tuple([y0, y1, None])

node_trace = go.Scatter(
    x=[],
    y=[],
    text=[],
    mode='markers',
    hoverinfo='text',
    marker=dict(
        showscale=True,
        colorscale='YlGnBu',
        reversescale=True,
        color=[],
        size=10,
        colorbar=dict(
            thickness=15,
            title='Node Connections',
            xanchor='left',
            titleside='right'
        ),
        line=dict(width=2)))

for node in G.nodes():
    x, y = G.nodes[node]['pos']
    node_trace['x'] += tuple([x])
    node_trace['y'] += tuple([y])

# ########COLOR NODES#########
for node, adjacencies in enumerate(G.adjacency()):
    node_trace['marker']['color']+=tuple([len(adjacencies[1])])
    node_info = '# of connections: '+str(len(adjacencies[1]))
    node_trace['text']+=tuple([node_info])

# ########CREATE GRAPH#########
fig = go.Figure(data=[edge_trace, node_trace],
             layout=go.Layout(
                title='<br>Network graph made with Python',
                titlefont=dict(size=16),
                showlegend=False,
                hovermode='closest',
                margin=dict(b=20,l=5,r=5,t=40),
                annotations=[ dict(
                    text="Python code: <a href='https://plot.ly/ipython-notebooks/network-graphs/'> https://plot.ly/ipython-notebooks/network-graphs/</a>",
                    showarrow=False,
                    xref="paper", yref="paper",
                    x=0.005, y=-0.002 ) ],
                xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
                yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)))

fig.show()

但是,我最终得到了这个错误:

  x0, y0 = G.nodes[edge[0]]['pos']
KeyError: 'pos'

一个 print(pos) 显示它是空的:

{}

我不确定错误在哪里。我相信它可能已经开始,因为我用节点和边填充了图形。我不知道如何纠正它...

【问题讨论】:

  • 我也有同样的问题。谢谢你的提问。

标签: python plotly networkx


【解决方案1】:

我修改了部分发布的代码。 从有问题的输出中直接给出节点和边。

import plotly.graph_objs as go
import networkx as nx
from plotly.subplots import make_subplots

x = []
y = []
G=nx.Graph()
#from question
edges = [('AddressA','AddressB'),('AddressA','AddressC')]
nodes = ['AddressA','AddressB','AddressC']
print ("nodes =", nodes)
print ("edges =", edges)

G.add_nodes_from(nodes, word1 = 'word2')

pos = nx.get_node_attributes(G,'word1')
G.add_edges_from(edges)
print("pos = ", pos)

这将打印 pos

注1:

如果我在 pos = nx.get_node_attributes(G,'word1') 之前的 G.add_edges_from ; 然后 pos = []

如果我在 G.add_edges_from 之前分配 pos = nx.get_node_attributes(G,'word1') 那么 pos 将正确打印

我得到如下输出:

nodes = ['AddressA', 'AddressB', 'AddressC']
edges = [('AddressA', 'AddressB'), ('AddressA', 'AddressC')]
pos =  {'AddressA': 'word2', 'AddressB': 'word2', 'AddressC': 'word2'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2014-08-18
    • 2023-03-28
    • 2021-11-16
    • 1970-01-01
    相关资源
    最近更新 更多