如何在 python networkx 中更改标签大小

How to change label size in python networkx

我的示例代码和结果图如下。

我想更改右上角图例中的节点大小。

具体来说,我试图使图例中的每个节点大小相等。

轴中节点的大小没有问题。


import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# define nodes, node types, and color range

nodes = list('abcdefghijkl')
nodeTypes = ['foo','bar','baz']
nodeColors = ['r', 'b', 'k']

# assign each node a type and color via a dictionaries
nodeTypeDict = dict(zip(nodeTypes, [nodes[:4],nodes[4:8],nodes[8:]]))
nodeColorDict = dict(zip(nodeTypes, nodeColors))
nodePos = dict(zip(nodes,[(np.random.random(),np.random.random()) 
                                        for i in range(len(nodes))]))

# generate the graph
g = nx.Graph()
g.add_nodes_from(nodes)

# create image canvas and axes
fig, ax = plt.subplots(1, figsize=(6,6))

# iterate each nodetype, changing colors and labels of the nodes
for nt, i in [('foo', 10), ('bar', 1), ('baz',20)]:
    # choose nodes and color for each iteration
    nlist = nodeTypeDict[nt]
    ncolor = nodeColorDict[nt]
    print(ncolor)
    # draw the graph
    nx.draw_networkx_nodes(g, 
                           pos=nodePos,
                           nodelist=nlist,
                           ax=ax, 
                           node_color=ncolor,
                           node_size = i,
                           label= nt)  # the label for each iteration is 
                                      # the node type
ax.legend(scatterpoints=1)                                      

您可以固定每个图例项的大小。

legend = ax.legend(scatterpoints=1)
for item in legend.legendHandles:
    item._sizes = [40]