networkx - change node size based on list or dictionary value

安稳与你 提交于 2019-12-04 08:05:48

2014/07/08 12:29PM: Updated to reflect comments from @user3358205

The problem is that the drawing functions in NetworkX require node_sizes to be input as a list of ints, while you are passing a list of strings. You can read the parameters to the drawing functions here.

Because I don't have the input files to your program, I can't reproduce your output. However, here's an example where you vary the size of the nodes by passing a list of node_sizes. Note that in the output, I am labeling each node by their size.

import sys, networkx as nx, matplotlib.pyplot as plt

# Create a list of 10 nodes numbered [0, 9]
nodes = range(10)
node_sizes = []
labels = {}
for n in nodes:
        node_sizes.append( 100 * n )
        labels[n] = 100 * n

# Node sizes: [0, 100, 200, 300, 400, 500, 600, 700, 800, 900]

# Connect each node to its successor
edges = [ (i, i+1) for i in range(len(nodes)-1) ]

# Create the graph and draw it with the node labels
g = nx.Graph()
g.add_nodes_from(nodes)
g.add_edges_from(edges)

nx.draw_random(g, node_size = node_sizes, labels=labels, with_labels=True)    
plt.show()

st.ph.n

With mdml's answer I was able to answer solve the problem. As it turns out I was passing a list to networkx for node sizes, although it did not appreciate the list. I was appending strings to the list, not integers. Changing v to and int() solves this problem, then I multiplied by 100, since some of the values were small, to make the node sizes relevant:

with open(cluster, "r") as f1:
     edges = [line.strip().split('\t') for line in f1]

with open(counts, "r") as f2:
     countsdic = defaultdict(list)
     for line in f2:
         k,v = line.strip().split()
         countsdic[k].append(v)

tmp = []

for el in sum(edges, []):
    tmp.append(el)

nodes = []

for t in tmp:
    if t not in nodes:
        nodes.append(t)

node_sizes = {}
for n in nodes:
    node_sizes[n] = ' '.join(countsdic[n])

sizes = []
for v in node_sizes.values():
    x = int(v) * 100
    sizes.append(x)

g = nx.Graph()
g.add_nodes_from(nodes)
g.add_edges_from(edges)

nx.draw_random(g, node_size = sizes)

plt.savefig(inp + "." + gtype + ".png")
plt.show()

The graph output I was looking for:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!