How to fix graphics being cut off when drawing NetworkX graphs with Matplotlib?

Viewed 1440

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()
1 Answers

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.

Related