问题
My dataframe has 3 columns, source , target and value. it looks like this
source target value BOBA FETT C-3PO 4 BOBA FETT CHEWBACCA 3 BOBA FETT DARTH VADER 8 BOBA FETT HAN 7
G = nx.from_pandas_edgelist(links,source='source',target='target', edge_attr='value')
I use this to add my edgelist
nx.draw_networkx_edge_labels(G,pos=nx.Graph(G),edge_labels={(u,v):w for u,v,w in G.edges(data='value')})
I tried this to show edge labels. I want the 'value' to be dispplayed as my edge label it gives this error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-23-d49aadc4a5f6> in <module>
1 ##try edge list here
----> 2 nx.draw_networkx_edge_labels(G,pos=nx.Graph(G),edge_labels={(u,v):w for u,v,w in G.edges(data='value')})
3
~\Anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py in draw_networkx_edge_labels(G, pos, edge_labels, label_pos, font_size, font_color, font_family, font_weight, alpha, bbox, ax, rotate, **kwds)
939 text_items = {}
940 for (n1, n2), label in labels.items():
--> 941 (x1, y1) = pos[n1]
942 (x2, y2) = pos[n2]
943 (x, y) = (x1 * label_pos + x2 * (1.0 - label_pos),
ValueError: too many values to unpack (expected 2)
回答1:
The value you provide to pos
should be a dictionary of node positions not the actual graph (there are a bunch of layout functions in networkx to build this. Something like this should fix it.
gpos = nx.circular_layout(G) # make a variable containing not positions
nx.draw_networkx(G,pos=gpos) # draw the graph
nx.draw_networkx_edge_labels(G,pos=gpos,edge_labels={(u,v):w for u,v,w in G.edges(data='value')}) # add edge labels
If you make multiple calls to plot the rest of the graph it's best to make a variable that contains your node positions and pass that same variable to the pos argument of the functions as above.
来源:https://stackoverflow.com/questions/64709312/error-displaying-edge-labels-from-pandas-dataframe-networkx-error-with-pos-valu