Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

networkx in a subplot is drawing nodes partially outside of axes frame

When I draw a networkx graph in a subplot, some of the nodes are partially cut off in the frame of the axes. I've tried this with all different types of graphs and layouts, it's always a problem. It always cuts off my nodes. It's as if networkx is drawing the graph on a bigger axes than is actually there.

Here is a minimal example

plt.subplot(2, 1, 1)
plt.scatter(range(10), range(10))

plt.subplot(2, 1, 2)
G = nx.erdos_renyi_graph(20, p=0.1)
nx.draw_networkx(G)
plt.show()

This is what I get from that. As you can see, node 0 and node 7 do not fit in the frame.

Minimal example

like image 896
chasmani Avatar asked Jan 24 '26 01:01

chasmani


2 Answers

Background

Your issue seems to be caused by the new autoscaling algorithm introduced with matplotlib 3.2.0. In the link it states, that the old algorithm did

for Axes.scatter it would make the limits large enough to not clip any markers in the scatter.

Hence, the new algorithm has stopped to do this, which results in the cute nodes.

How to fix your problem

You can simply increase the length of your axis:

import networkx as nx
import matplotlib.pylab as plt

figure = plt.subplot(2, 1, 1)
plt.scatter(range(10), range(10))

plt.subplot(2, 1, 2)
G = nx.erdos_renyi_graph(20, p=0.1)
nx.draw_networkx(G)
axis = plt.gca()
# maybe smaller factors work as well, but 1.1 works fine for this minimal example
axis.set_xlim([1.1*x for x in axis.get_xlim()])
axis.set_ylim([1.1*y for y in axis.get_ylim()])
plt.show()
like image 169
Sparky05 Avatar answered Jan 25 '26 15:01

Sparky05


Just playing a with the figure sizes should do the trick. Try setting a larger figure size through the subplots' figsize parameter:

f, axs = plt.subplots(2,1,figsize=(15,15))
axs[0].scatter(range(10), range(10))
G = nx.erdos_renyi_graph(20, p=0.1)
nx.draw_networkx(G, ax=axs[1], node_color='lightgreen')

enter image description here


You can also look into networkX' layouts, such as spring_layout, which allow to encapsulate the nodes within a given box size, specified by a scale parameter. Here's an example:

f, axs = plt.subplots(2,1,figsize=(15,15))
axs[0].scatter(range(10), range(10))
G = nx.erdos_renyi_graph(20, p=0.05)
pos = nx.spring_layout(G, k=0.7, scale=0.05)
nx.draw_networkx(G, pos=pos, ax=axs[1], node_color='lightgreen')

enter image description here

like image 24
yatu Avatar answered Jan 25 '26 15:01

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!