paulbrodersen / netgraph

Publication-quality network visualisations in python
GNU General Public License v3.0
660 stars 39 forks source link

Proper format for entering node_labels ? #64

Closed fishbacp closed 1 year ago

fishbacp commented 1 year ago

I've run the sample plot_10_community_layout.py using partition_sizes = [3,4,3]. Suppose my node labels are the letters A-J. I tried setting node_labels={0:'A',1:'B',2:'C',3:'D',4:'E',5:'F',6:'G',7:'H',8:'I',9:'J'} and passing node_labels=node_labels as an argument to Graph but received the error message below. Is there a different way I should enter my labels?

  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/netgraph/_main.py", line 1347, in __init__
    super().__init__(edges, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/netgraph/_main.py", line 315, in __init__
    self.node_label_fontdict = self._initialize_node_label_fontdict(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/netgraph/_main.py", line 845, in _initialize_node_label_fontdict
    size = self._get_font_size(node_labels, node_label_fontdict) * 0.75 # conservative fudge factor
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/netgraph/_main.py", line 859, in _get_font_size
    artist = self.node_artists[node]
KeyError: 10
paulbrodersen commented 1 year ago

That is the correct format for node_labels and on my machine this works as intended:

import matplotlib.pyplot as plt
import networkx as nx

from netgraph import Graph

# create a modular graph
partition_sizes = [3, 4, 3]
g = nx.random_partition_graph(partition_sizes, 1.0, 0.5)

# create a dictionary that maps nodes to the community they belong to
node_to_community = dict()
node = 0
for community_id, size in enumerate(partition_sizes):
    for _ in range(size):
        node_to_community[node] = community_id
        node += 1

community_to_color = {
    0 : 'tab:blue',
    1 : 'tab:orange',
    2 : 'tab:green',
    3 : 'tab:red',
}
node_color = {node: community_to_color[community_id] for node, community_id in node_to_community.items()}
node_labels = dict(zip(range(10), 'abcdefghij'))

Graph(g,
      node_color=node_color, node_labels=node_labels, node_edge_width=0, edge_alpha=0.1,
      node_layout='community', node_layout_kwargs=dict(node_to_community=node_to_community),
      edge_layout='bundled', edge_layout_kwargs=dict(k=2000),
)

plt.show()

Figure_1

Since you closed the issue yourself, did you work out what was going wrong?