Reputation: 175
I am trying to follow the tutorial given here code posted below for "reproducibility" but I get stuck when I try the draw() for the first visualization
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def draw(G, pos, measures, measure_name):
nodes = nx.draw_networkx_nodes
(G, pos, node_size=250,cmap=plt.cm.plasma,
node_color=measures.values(),
nodelist=measures.keys())
nodes.set_norm(mcolors.SymLogNorm(linthresh=0.01, linscale=1))
edges = nx.draw_networkx_edges(G, pos)
plt.title(measure_name)
plt.colorbar(nodes)
plt.axis('off')
plt.show()
G = nx.karate_club_graph()
pos = nx.spring_layout(G)
draw(G, pos, nx.degree_centrality(G), 'Degree Centrality')
The traceback keeps showing the error: float() argument must be a string or a number, not 'dict_values'
based on this question
I think that it is a python 3 problem. I tried
draw(G, np.array(list(pos.values())).astype(float),
nx.degree_centrality(G), 'Degree Centrality')
but I am still getting the same error. Any advice?
Upvotes: 0
Views: 891
Reputation: 11929
The code works fine with python2.7.
The reason is the type of measures.values()
which is different between Python 2 and 3.
Indeed, while in python 2.7 dict.values returns list, in python 3.x it returns a view of the dictionary’s values.
d={"k":"v"}
#python 2.7
type(d.values()) ---> <type 'list'>
#python 3.x
type(d.values()) ---> <class 'dict_values'>
Thus, you have a TypeError
exception raised as node_color
is expected to be a string or an array of floats and the argument has type dict_values
. See the documentation here for more details.
To solve the problem you only need to change the way the node colors are passed to the draw_networkx_nodes
function.
For instance, you could use a list as follows:
nodes = nx.draw_networkx_nodes(G, pos, node_size=250, cmap=plt.cm.plasma, node_color=list(measures.values()),nodelist=measures.keys())
Upvotes: 3