0

I am plotting a table of graphs, but the nodes overlap the edges of the boxes.

Is there an option to scale the graphs down so as to stop the nodes going over?

I see lots of questions about adjusting spacing between the cells, but I want to scale down the graphs so they fit in the cells.

Here is the code for a simple example of the trouble:

from networkx.drawing.nx_agraph import graphviz_layout
import matplotlib.pyplot as plt
import networkx as nx


plt.figure(1, figsize=(9, 9))

G=nx.complete_multipartite_graph(1,1,1)
        
pos = graphviz_layout(G, prog="neato")  
plt.subplot(9,9,1)
nx.draw(G, pos, node_size=50,  with_labels=False)

G=nx.complete_multipartite_graph(1,1,2)
pos = graphviz_layout(G, prog="neato")  
plt.subplot(9,9,11)
nx.draw(G, pos)

plt.show()

Here is the output this gives

DapperDuck
  • 2,728
  • 1
  • 9
  • 21
Phil168
  • 1
  • 2
  • You can take a look at https://stackoverflow.com/a/62920958/11339311 and in the linked answers. – Sparky05 Jan 29 '21 at 15:07
  • Thanks, this does indeed shrink the second graph down, but it it does not center it so it still goes off the left. Is there a way to center it as well? And how do I adjust this to work with both graphs? – Phil168 Jan 29 '21 at 16:31

1 Answers1

0

OK this is an extension of the suggestion of Sparky05: the xlim and ylim are a pair of numbers we can set arbitrarily, so here is some code to scale them, but keeping the midpoint fixed, in case its useful to anyone else.

from networkx.drawing.nx_agraph import graphviz_layout
import matplotlib.pyplot as plt
import networkx as nx

def scalegraph(sf):  # scale graph by scalefactor = sf, keeping it centred
    plt.axis('off')
    axis = plt.gca()
    xlim=list(axis.get_xlim())
    ylim=list(axis.get_ylim())
    xav=sum(xlim)/2
    dx=(xlim[1]-xlim[0])/2
    yav=sum(ylim)/2
    dy=(ylim[1]-ylim[0])/2
    axis.set_xlim([xav-sf*dx,xav+sf*dx])
    axis.set_ylim([yav-sf*dy,yav+sf*dy])


plt.figure(1, figsize=(9, 9))

G=nx.complete_multipartite_graph(1,1,1)
        
pos = graphviz_layout(G, prog="neato")  
plt.subplot(9,9,1)
nx.draw(G, pos, node_size=50,  with_labels=False)

scalegraph(1.2)

G=nx.complete_multipartite_graph(1,1,2)
pos = graphviz_layout(G, prog="neato")  
plt.subplot(9,9,11)
nx.draw(G, pos)

scalegraph(1.5)

plt.show()
Phil168
  • 1
  • 2