3

I am using NetworkX and Matplotlib to draw nodes, but the nodes are sometimes being cut off at the edge of the graphic. Is there a setting to increase the margins or prevent them from being cut off?

Image: Nodes being cut off at the edge of the graphic

Example program:

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

adjacency_matrix = np.array([[1,0,0,0,0,0,1,0],[0,1,1,1,1,0,0,0],[0,1,1,0,0,0,0,0],[0,1,0,1,0,0,0,0],
    [0,1,0,0,1,1,0,0],[0,0,0,0,1,1,1,1],[1,0,0,0,0,1,1,0],[0,0,0,0,0,1,0,1]])

nx_graph = nx.from_numpy_matrix(adjacency_matrix)
pos = nx.networkx.kamada_kawai_layout(nx_graph)

nx.draw_networkx_nodes(nx_graph, pos, node_color="#000000", node_size=10000)

nx.draw_networkx_edges(nx_graph, pos, color="#808080", alpha=0.2, width=2.0)

plt.axis('off')
plt.tight_layout()
plt.show()
Sparky05
  • 4,692
  • 1
  • 10
  • 27

1 Answers1

7

You can scale the axis to avoid that the nodes are cut off

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

adjacency_matrix = np.array([[1,0,0,0,0,0,1,0],[0,1,1,1,1,0,0,0],[0,1,1,0,0,0,0,0],[0,1,0,1,0,0,0,0],
    [0,1,0,0,1,1,0,0],[0,0,0,0,1,1,1,1],[1,0,0,0,0,1,1,0],[0,0,0,0,0,1,0,1]])

nx_graph = nx.from_numpy_matrix(adjacency_matrix)
pos = nx.networkx.kamada_kawai_layout(nx_graph)

nx.draw_networkx_nodes(nx_graph, pos, node_color="#000000", node_size=10000)

nx.draw_networkx_edges(nx_graph, pos, color="#808080", alpha=0.2, width=2.0)

plt.axis('off')
axis = plt.gca()
axis.set_xlim([1.2*x for x in axis.get_xlim()])
axis.set_ylim([1.2*y for y in axis.get_ylim()])
plt.tight_layout()
plt.show()

Depending on your node size you may need to vary the factor (1.2). In your given example this value worked. More information in my answer of a related question.

Sparky05
  • 4,692
  • 1
  • 10
  • 27
  • Is there another way without rescaling/shrinking the whole graph, and just widening the borders? – Maximilian Levine Jul 16 '20 at 20:01
  • As discussed in the linked question, you can also increase the `figsize` or (to return to the old variant of autoscaling) use an old version of matplotlib. – Sparky05 Jul 17 '20 at 07:52