如何在绘图中控制网络图的边缘权重?

时间:2019-05-16 10:18:49

标签: python graph plotly data-visualization networkx

我有一个包含4列的数据集:Person 1Person 2Family IDNo of mutual friends。我想制作一个人1连接到人2的网络图。我希望​​边缘权重基于共同朋友的数量。我该怎么办?

我尝试将边缘的权重分配给整个共同的朋友列,但是我收到一个错误消息,说它到目前为止仅接受标量值,这与可以接受列表等的节点跟踪不同:

edge_trace = go.Scatter(
    x=[],
    y=[],
    line=dict(width=df['No of mutual friends],color='#888'),
    hoverinfo='none',
    mode='lines')
>>> ValueError: Invalid value of type 'pandas.core.series.Series' received for the 'width' property of scatter.line

到目前为止,我的代码基于networkx和documentation上的plotly的this code

import pandas as pd
import plotly.graph_objs as go
import networkx as nx
from plotly.offline import download_plotlyjs, init_notebook_mode,  iplot, plot

init_notebook_mode(connected=True)

df = pd.read_csv('dataset.csv')
df.sort_values(['No of mutual friends'],ascending=False,inplace=True)

num_nodes = len(df)
# edge = df['itemset'][:num_nodes]

#create graph G
G = nx.Graph()
#G.add_nodes_from(node)
for i in range(len(df)):
    G.add_weighted_edges_from([(df.Person_1[i], df.Person_2[i], df['No of mutual friends][i])])

# adjust node size according to degree, etc
d = nx.degree(G)
node_sizes = []
for i in d:
    _, value = i
    node_sizes.append(10*value+5)

#get a x,y position for each node  
pos = nx.circular_layout(G)

#add a pos attribute to each node
for node in G.nodes:
    G.nodes[node]['pos'] = list(pos[node])

pos=nx.get_node_attributes(G,'pos')


dmin=1
ncenter=0
for n in pos:
    x,y=pos[n]
    d=(x-0.5)**2+(y-0.5)**2
    if d<dmin:
        ncenter=n
        dmin=d

p=nx.single_source_shortest_path_length(G,ncenter)

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

edge_trace['line'] = dict(width=0.5,color='#888')

for edge in G.edges():
    x0, y0 = G.node[edge[0]]['pos']
    x1, y1 = G.node[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 options
        #'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' |
        #'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' |
        #'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' |
        colorscale='Viridis',
        reversescale=True,
        color=[],
        size=node_sizes,
        colorbar=dict(
            thickness=15,
            title='Node Connections',
            xanchor='left',
            titleside='right'
        ),  
        line=dict(width=2)))

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

#add color to node points
for node, adjacencies in enumerate(G.adjacency()):
    node_trace['marker']['color']+=tuple([len(adjacencies[1])])
    node_info = 'Name: ' + str(adjacencies[0]) + '<br># of connections: '+str(len(adjacencies[1]))
    node_trace['text']+=tuple([node_info])

fig = go.Figure(data=[edge_trace, node_trace],
             layout=go.Layout(
                title='<br>Network Graph of Family Relationships',
                titlefont=dict(size=16),
                showlegend=False,
                hovermode='closest',
                width=880,
                height=800,
                margin=dict(b=20,l=5,r=5,t=40),
                annotations=[ dict(
                    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)))
iplot(fig)

enter image description here

0 个答案:

没有答案