4

Drawing a huge graph with networkX and matplotlib

I'm essentially reasking the linked question. I think I can do a better job explaining the question. With mathplotlib.show() called on a large graph, the default is a zoomed out, clustered output. My desired endstate is to use the mathplotlib.savefig() to save the plot for use in a report. However, the savefig() output is too zoomed out, too general. Changing the image size or dpi DOES NOT fix this. Only makes the zoomed out image bigger. Is there are a way to zoom in to the graph and save that without using the UI? With the UI, I can zoom in, spread the nodes out, and center around a node in question, but I do not know how to do this automatically.

Relevant code:

    nx.draw(G,pos,node_color=colorvalues, with_labels = False,node_size=values)
    fig.set_size_inches(11,8.5)
    if show ==0:
        plt.show()
    if show ==1:   
        plt.savefig(name+" coremem.png",bbox_inches=0,orientation='landscape',pad_inches=0.1)
Community
  • 1
  • 1
Brad
  • 73
  • 1
  • 4

2 Answers2

3

You could use ax.set_xlim and ax.set_ylim to set the x and y ranges of the plot. For example,

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

filename = '/tmp/graph.png'
G = nx.complete_graph(10)
pos = nx.spring_layout(G)
xy = np.row_stack([point for key, point in pos.iteritems()])
x, y = np.median(xy, axis=0)
fig, ax = plt.subplots()
nx.draw(G, pos, with_labels=False, node_size=1)
ax.set_xlim(x-0.25, x+0.25)
ax.set_ylim(y-0.25, y+0.25)
plt.savefig(filename, bbox_inches=0, orientation='landscape', pad_inches=0.1)

enter image description here


To find out the original limits (before calling ax.set_xlim and ax.set_ylim), use

>>> ax.get_xlim()
(-0.20000000000000001, 1.2000000000000002)

ax.get_ylim()
(-0.20000000000000001, 1.2000000000000002)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Thank you. Such a simple command, silly I overlooked it. I'm currently trying to figure out a mathematical way to automatically determine the center mass of the network and zoom to it. For example, I have lists for the xvalues and yvalues respectively for the nodes. I've done ax.set_xlim(min(xval)-.25,max(xval)+.25), and same for yvalues. The .25 is a good buffer. My problem is that in a large graph in spring_layout, two nodes that are connected to each other, but unconnected from the rest will be so far away that it ruins my algorithm... I'll be working on that... – Brad Jul 09 '13 at 13:42
  • Instead of the center of mass, you could use the median of the `x` and `y` positions of the nodes as given by `pos`. I've added some code above to show what I mean. – unutbu Jul 09 '13 at 14:41
0

You can't zoom so to speak to my knowledge, but you can set the axes. For example if your original graph goes from 1-100 on both axes, you can programmatically make it go from only 30 to 40 and save that.

BenjaminCohen
  • 276
  • 2
  • 9