Saving a matplotlib/networkx figure without margins

save figure without margin matplotlib
matplotlib save image without white space
matplotlib increase margins
matplotlib save without border
matplotlib margins
matplotlib no margin savefig
matplotlib savefig size
matplotlib remove whitespace

When I draw a figure using matplotlib how do I save it without extra margins? Usually when I save it as

plt.savefig("figure.png") # or .pdf

I get it with some margins:

Example:

import matplotlib.pyplot as plt
import networkx as nx

G=nx.Graph()

G.add_edge('a','b',weight=1)
G.add_edge('a','c',weight=1)
G.add_edge('a','d',weight=1)
G.add_edge('a','e',weight=1)
G.add_edge('a','f',weight=1)
G.add_edge('a','g',weight=1)

pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,node_size=1200,node_shape='o',node_color='0.75')

nx.draw_networkx_edges(G,pos,
                width=2,edge_color='b')

plt.axis('off')
plt.savefig("degree.png", bbox_inches="tight")
plt.show() 

Update 2:

The spaces are set inside the axes.. This is clear if I remove plt.axis('off') So I think there is some trick to use with the package Networkx.

add the codes below to control plot limits before saving.

try different values of cut, like from 1.05 to 1.50, until you see fit.

# adjust the plot limits
cut = 1.05
xmax= cut*max(xx for xx,yy in pos.values())
ymax= cut*max(yy for xx,yy in pos.values())
plt.xlim(0,xmax)
plt.ylim(0,ymax)

Removing white space around a saved image in matplotlib, Reduce left and right margins in matplotlib plot def save(filepath, fig=None): '''​Save the current image with no whitespace Example filepath: "myfig.png" or  Saving a matplotlib/networkx figure without margins (3) A bit of a hack, but if you use nx.draw, then it does a tighter fit. So you could do. nx. draw (G, pos, node_size = 1200, node_shape = 'o', node_color = '0.75', edgelist = [])

Try plt.savefig("figure.png", bbox_inches="tight").

Edit: Ah, you didn't mention you were using networkx (although now I see it's listed in a tag). bbox_inches="tight" is the way to crop the figure tightly. I don't know what networkx is doing, but I imagine it's setting some plot parameters that are adding extra space to the axes. You should look for a solution in networkx rather than matplotlib. (It may be, for instance, that networkx is adding the space inside the axes, not the figure; what does it look like if you remove that axis('off') call?)

python Saving a matplotlibnetworkx figure without margins?, You should look for a solution in networkx rather than matplotlib. (It may be, for instance, that networkx is adding the space inside the axes, not the figure; what  import matplotlib.pyplot as plt plt.plot(whatever) plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1) This will work for both the figure on screen and saved to a file, and it is the right function to call even if you don't have multiple plots on the one figure.

Use the following:

plt.margins(0.0)

draw_networkx, Draw the graph with Matplotlib with options for node positions, labeling, titles, and many See draw() for simple drawing without labels or axes. edgelist (list, optional (default=G.edges())) – Draw only specified edges; node_size (scalar or  A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages. If format is not set, then the output format is inferred from the extension of fname , if any, and from rcParams["savefig.format"] (default: 'png') otherwise.

Without knowing the specifics of networkx I cannot be certain that this will work, but to remove the whitespace completely from the outside of an axes in matplotlib, you can do something along the lines of:

import matplotlib.pyplot as plt
ax = plt.axes([0, 0, 1, 1])
plt.plot(range(10))

Creating a graph, Create an empty graph with no nodes and no edges. (Note: Python's None object should not be used as a node as it determines whether Graph.edges() , and Graph.neighbors() , iterator versions (e.g. Graph.edges_iter() ) can save you​  import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,10)) plt.imshow(img) # your image here plt.axis("off") plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0) plt.savefig("example2.png", box_inches='tight', dpi=100) plt.show()

A bit of a hack, but if you use nx.draw, then it does a tighter fit.

So you could do

nx.draw(G,pos,node_size=1200,node_shape='o',node_color='0.75', edgelist = [])

which just draws the nodes and no edges. Then it's fine to do

nx.draw_networkx_edges(G, pos, width=2, edge_color='b')

Labels And Colors, #!/usr/bin/env python """ Draw a graph with matplotlib, color by degree. alpha=​0.8) # edges nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5) plt.axis('off'​) plt.savefig("labels_and_colors.png") # save as png plt.show() # display. Matplotlib is capable of creating all manner of graphs, plots, charts, histograms, and much more. In most cases, matplotlib will simply output the chart to your viewport when the .show() method is invoked, but we’ll briefly explore how to save a matplotlib creation to an actual file on disk. Using matplotlib

matplotlib.pyplot.savefig, Save the current figure. Hence, if fname is not a path or has no extension, remember to specify format to ensure that the correct backend is used. Reduce left and right margins in matplotlib plot | this answer edited Aug 7 '12 at 13:50 answered Aug 7 '12 at 13:39 Hooked 32.2k 13 108 169 What I try to do is to draw a graph on a figure by NetworkX then save it as an image. The problem - whiteSpace could be related to NetworkX commands. Anyway, I updated the question.

matplotlib.pyplot.margins, If no arguments (positional or otherwise) are provided, the current margins will remain in place and simply be returned. Specifying any margin  import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111) ax.plot(range(10),range(10)) ax.set_aspect('equal') plt.tight_layout() tight_layout eliminates some of the margin, but not all of the margins.

Python, NetworkX is not a graph visualising package but basic drawing with Matplotlib is included Step 4 : Use savefig("filename.png") function of matplotlib.pyplot to save the drawing of graph in filename.png file. Graph with no label using Python Dash and Plotly · Link Prediction - Predict edges in a network using Networkx  matplotlib.pyplot.margins¶ matplotlib.pyplot.margins (*margins, x=None, y=None, tight=True) [source] ¶ Set or retrieve autoscaling margins. The padding added to each limit of the axes is the margin times the data interval. All input parameters must be floats within the range [0, 1].

Comments
  • Thank you very much. It works but with removing some small part of the limits of the figure. I do not get the figure complete. So i think i just need to modify it somehow.
  • you can try a more conservative cut (1.10 or 1.05 rather than 1.02), just change it until the canvas fits.
  • @Aya you may want to ask the question on the networkx mailinglist, and also, you can try to wrap the above codes into a function so that you call it with whatever cut you want without copy&paste all the time.
  • NetworkX has to figure what the x limits are and y limits are based on the data and the node shape. There is just some simple padding of the exact data values to account for the node shape. You can adjust that using plt.xlim() and plt.ylim() as described above. Calling those functions with no arguments will give you the current limits.
  • this doesnt work. I tried with different values of cut, but i always get my figure 'cropped'
  • Can you give an example of what you mean by "margins"?
  • thank you. I do not want the figure to be saved with extra white spaces. I just want the borders to close the limits of the figure exactly. Is this clear?
  • This is exactly what bbox_inches="tight" does. Can you explain how it doesn't do what you want? Also what version of matplotlib are you using?
  • I think this is the version: Python 2.7 matplotlib-1.1.0
  • yes, you are right. the spaces are inside the axes. Thank you
  • Jurkiewics It worked with margins(0.15). margins(0.0) don't draw the graph totaly into the page.