1

Some background...

I am a beginner to python and networkx...

I have a csv file with multiple columns.

I have extracted the columns that contained the sender and receiver addresses and put them into lists like so:

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))))

A quick print of my G.nodes() and G.edges() gives me the following output:

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

where edges = [('senderaddress','receiveraddress')]

My goal

I wish to use networkx to plot out connections between senders and receivers.

I am using this page as reference.

This is my current code:

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()

However, I end up with this error:

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

A print(pos) showed that it was empty:

{}

I'm not sure where the error lies. I believe it may have started since I populated the graph with nodes and edges. I am not sure how to rectify it though...

1
  • I have the same question. Thank you for asking. Commented Feb 28, 2020 at 1:18

1 Answer 1

1

I modified some part of the posted code. With nodes and edges given directly, from the output shown in question.

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)

This will print pos

Note1:

If I G.add_edges_from before pos = nx.get_node_attributes(G,'word1') ; then pos = []

If I assign pos = nx.get_node_attributes(G,'word1') before G.add_edges_from then pos will print correctly

I get output as follows:

nodes = ['AddressA', 'AddressB', 'AddressC']
edges = [('AddressA', 'AddressB'), ('AddressA', 'AddressC')]
pos =  {'AddressA': 'word2', 'AddressB': 'word2', 'AddressC': 'word2'}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.