I need to take an image and save it after some process. The figure looks fine when I display it, but after saving the figure, I got some white space around the saved image. I have tried the 'tight' option for savefig method, did not work either. The code:
I am trying to draw a basic graph by using NetworkX on a figure and save it. I realized that without graph it works, but when added a graph I get white space around the saved image;
I cannot claim I know exactly why or how my “solution” works, but this is what I had to do when I wanted to plot the outline of a couple of aerofoil sections — without white margins — to a PDF file.
(Note that I used matplotlib inside an IPython notebook, with the -pylab flag.)
I have tried to deactivate different parts of this, but this always lead to a white margin somewhere. You may even have modify this to keep fat lines near the limits of the figure from being shaved by the lack of margins.
def save(filepath, fig=None):'''Save the current image with no whitespace
Example filepath: "myfig.png" or r"C:\myfig.pdf"
'''import matplotlib.pyplot as plt
ifnot fig:
fig = plt.gcf()
plt.subplots_adjust(0,0,1,1,0,0)for ax in fig.axes:
ax.axis('off')
ax.margins(0,0)
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
fig.savefig(filepath, pad_inches =0, bbox_inches='tight')
The following function incorporates johannes-s answer above. I have tested it with plt.figure and plt.subplots() with multiple axes, and it works nicely.
def save(filepath, fig=None):
'''Save the current image with no whitespace
Example filepath: "myfig.png" or r"C:\myfig.pdf"
'''
import matplotlib.pyplot as plt
if not fig:
fig = plt.gcf()
plt.subplots_adjust(0,0,1,1,0,0)
for ax in fig.axes:
ax.axis('off')
ax.margins(0,0)
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
fig.savefig(filepath, pad_inches = 0, bbox_inches='tight')
The most straightforward method is to use plt.tight_layout transformation which is actually more preferable as it doesn’t do unnecessary cropping when using plt.savefig
import matplotlib as plt
plt.plot([1,2,3], [1,2,3])
plt.tight_layout(pad=0)
plt.savefig('plot.png')
However, this may not be preferable for complex plots that modifies the figure. Refer to top answers that uses plt.subplots_adjust if that’s the case.
回答 11
这对我有用,将用imshow绘制的numpy数组保存到文件
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()