Removing white space around a saved image in matplotlib
I need to take an image and save it after some process. The figure looks fine when I display it, but when I save 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:
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
fig = plt.figure(1)
img = mpimg.imread(path)
plt.imshow(img)
ax=fig.add_subplot(1,1,1)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches=extent)
plt.axis('off')
plt.show()
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;
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1,3)
G.add_edge(1,2)
pos = {1:[100,120], 2:[200,300], 3:[50,75]}
fig = plt.figure(1)
img = mpimg.imread("C:\images\1.jpg")
plt.imshow(img)
ax=fig.add_subplot(1,1,1)
nx.draw(G, pos=pos)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches = extent)
plt.axis('off')
plt.show()
python matplotlib
add a comment |
I need to take an image and save it after some process. The figure looks fine when I display it, but when I save 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:
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
fig = plt.figure(1)
img = mpimg.imread(path)
plt.imshow(img)
ax=fig.add_subplot(1,1,1)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches=extent)
plt.axis('off')
plt.show()
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;
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1,3)
G.add_edge(1,2)
pos = {1:[100,120], 2:[200,300], 3:[50,75]}
fig = plt.figure(1)
img = mpimg.imread("C:\images\1.jpg")
plt.imshow(img)
ax=fig.add_subplot(1,1,1)
nx.draw(G, pos=pos)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches = extent)
plt.axis('off')
plt.show()
python matplotlib
1
Possible duplicate of Saving a matplotlib/networkx figure without margins
– Joel
Oct 13 '15 at 10:03
What really worked for me was to crop the pdf using another tool, such as pdfcrop.
– toliveira
Jun 12 '18 at 11:33
add a comment |
I need to take an image and save it after some process. The figure looks fine when I display it, but when I save 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:
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
fig = plt.figure(1)
img = mpimg.imread(path)
plt.imshow(img)
ax=fig.add_subplot(1,1,1)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches=extent)
plt.axis('off')
plt.show()
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;
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1,3)
G.add_edge(1,2)
pos = {1:[100,120], 2:[200,300], 3:[50,75]}
fig = plt.figure(1)
img = mpimg.imread("C:\images\1.jpg")
plt.imshow(img)
ax=fig.add_subplot(1,1,1)
nx.draw(G, pos=pos)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches = extent)
plt.axis('off')
plt.show()
python matplotlib
I need to take an image and save it after some process. The figure looks fine when I display it, but when I save 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:
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
fig = plt.figure(1)
img = mpimg.imread(path)
plt.imshow(img)
ax=fig.add_subplot(1,1,1)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches=extent)
plt.axis('off')
plt.show()
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;
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1,3)
G.add_edge(1,2)
pos = {1:[100,120], 2:[200,300], 3:[50,75]}
fig = plt.figure(1)
img = mpimg.imread("C:\images\1.jpg")
plt.imshow(img)
ax=fig.add_subplot(1,1,1)
nx.draw(G, pos=pos)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches = extent)
plt.axis('off')
plt.show()
python matplotlib
python matplotlib
edited Aug 7 '12 at 16:44
Ahmet Tuğrul Bayrak
asked Aug 7 '12 at 1:02
Ahmet Tuğrul BayrakAhmet Tuğrul Bayrak
6041518
6041518
1
Possible duplicate of Saving a matplotlib/networkx figure without margins
– Joel
Oct 13 '15 at 10:03
What really worked for me was to crop the pdf using another tool, such as pdfcrop.
– toliveira
Jun 12 '18 at 11:33
add a comment |
1
Possible duplicate of Saving a matplotlib/networkx figure without margins
– Joel
Oct 13 '15 at 10:03
What really worked for me was to crop the pdf using another tool, such as pdfcrop.
– toliveira
Jun 12 '18 at 11:33
1
1
Possible duplicate of Saving a matplotlib/networkx figure without margins
– Joel
Oct 13 '15 at 10:03
Possible duplicate of Saving a matplotlib/networkx figure without margins
– Joel
Oct 13 '15 at 10:03
What really worked for me was to crop the pdf using another tool, such as pdfcrop.
– toliveira
Jun 12 '18 at 11:33
What really worked for me was to crop the pdf using another tool, such as pdfcrop.
– toliveira
Jun 12 '18 at 11:33
add a comment |
8 Answers
8
active
oldest
votes
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.)
gca().set_axis_off()
subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
margins(0,0)
gca().xaxis.set_major_locator(NullLocator())
gca().yaxis.set_major_locator(NullLocator())
savefig("filename.pdf", bbox_inches = 'tight',
pad_inches = 0)
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.
5
Finally something that works, thank you so much! By the way, in my case only the two lines usingset_major_locator
were necessary.
– Florian Brucker
Oct 28 '15 at 17:54
3
I've spent the last hour trying various things and could not get rid of a 1px white border. This was the only thing which worked - specifically thepad_inches=0
which other answers do not mention.
– Annan
May 16 '16 at 17:54
3
The only answer that actually worked!
– Sleepyhead
May 24 '16 at 8:18
7
pad_inches
helped me.
– Myles Baker
Aug 15 '16 at 4:56
3
matplotlib.ticker.NullLocator()
– Joop
Jun 14 '17 at 13:14
|
show 9 more comments
You can remove the white space padding by setting bbox_inches="tight"
in savefig
:
plt.savefig("test.png",bbox_inches='tight')
You'll have to put the argument to bbox_inches
as a string, perhaps this is why it didn't work earlier for you.
Possible duplicates:
Matplotlib plots: removing axis, legends and white spaces
How to set the margins for a matplotlib figure?
Reduce left and right margins in matplotlib plot
1
If you have multiple subplots and want to save each of them, you can use this withfig.savefig()
too. (plt.savefig()
will not work in that case.)
– Abhranil Das
Apr 21 '13 at 12:06
18
That's not quite right. When you use thatbbox_inches
option, there's another default that leaves some space. If you really want to get rid of everything, you need to also usepad_inches=0.0
. Of course, such tight padding frequently cuts off, e.g., exponents...
– Mike
Dec 19 '14 at 16:46
16
still some whitespace left...
– Sleepyhead
May 24 '16 at 8:15
4
To remove the black edge as well, you may need to setpad_inches=-0.1
– lenhhoxung
Oct 12 '17 at 14:09
3
This simply doesn't work, you still get whitespace around the figure. Setting the transparent option (as mentioned in some answers) doesn't really help either, the whitespace is still there, it's only transparent.
– BjornW
Apr 7 '18 at 10:50
|
show 4 more comments
I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:
plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)
2
transparent=True
will make it seem like there's no problem but it will just hide white space, image dimensions won't be ok.
– Vlady Veselinov
Jul 28 '18 at 16:34
add a comment |
I found the following codes work perfectly for the job.
fig = plt.figure(figsize=[6,6])
ax = fig.add_subplot(111)
ax.imshow(data)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
plt.savefig('data.png', dpi=400, bbox_inches='tight',pad_inches=0)
2
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
– Tim Diekmann
May 24 '18 at 15:26
add a comment |
After trying the above answers with no success (and a slew of other stack posts) what finally worked for me was just
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig("myfig.pdf")
Importantly this does not include the bbox or padding arguments. For unclear reasons, when I had the bbox argument included in my savefig, my figure was shifted right and upwards off-center.
add a comment |
i followed this sequence and it worked like a charm.
plt.axis("off")
fig=plt.imshow(image array,interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('destination_path.pdf',bbox_inches='tight', pad_inches = 0, format='pdf', dpi=1200)
add a comment |
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')
add a comment |
This works for me saving a numpy array plotted with imshow to file
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()
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11837979%2fremoving-white-space-around-a-saved-image-in-matplotlib%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
8 Answers
8
active
oldest
votes
8 Answers
8
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.)
gca().set_axis_off()
subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
margins(0,0)
gca().xaxis.set_major_locator(NullLocator())
gca().yaxis.set_major_locator(NullLocator())
savefig("filename.pdf", bbox_inches = 'tight',
pad_inches = 0)
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.
5
Finally something that works, thank you so much! By the way, in my case only the two lines usingset_major_locator
were necessary.
– Florian Brucker
Oct 28 '15 at 17:54
3
I've spent the last hour trying various things and could not get rid of a 1px white border. This was the only thing which worked - specifically thepad_inches=0
which other answers do not mention.
– Annan
May 16 '16 at 17:54
3
The only answer that actually worked!
– Sleepyhead
May 24 '16 at 8:18
7
pad_inches
helped me.
– Myles Baker
Aug 15 '16 at 4:56
3
matplotlib.ticker.NullLocator()
– Joop
Jun 14 '17 at 13:14
|
show 9 more comments
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.)
gca().set_axis_off()
subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
margins(0,0)
gca().xaxis.set_major_locator(NullLocator())
gca().yaxis.set_major_locator(NullLocator())
savefig("filename.pdf", bbox_inches = 'tight',
pad_inches = 0)
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.
5
Finally something that works, thank you so much! By the way, in my case only the two lines usingset_major_locator
were necessary.
– Florian Brucker
Oct 28 '15 at 17:54
3
I've spent the last hour trying various things and could not get rid of a 1px white border. This was the only thing which worked - specifically thepad_inches=0
which other answers do not mention.
– Annan
May 16 '16 at 17:54
3
The only answer that actually worked!
– Sleepyhead
May 24 '16 at 8:18
7
pad_inches
helped me.
– Myles Baker
Aug 15 '16 at 4:56
3
matplotlib.ticker.NullLocator()
– Joop
Jun 14 '17 at 13:14
|
show 9 more comments
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.)
gca().set_axis_off()
subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
margins(0,0)
gca().xaxis.set_major_locator(NullLocator())
gca().yaxis.set_major_locator(NullLocator())
savefig("filename.pdf", bbox_inches = 'tight',
pad_inches = 0)
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.
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.)
gca().set_axis_off()
subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
margins(0,0)
gca().xaxis.set_major_locator(NullLocator())
gca().yaxis.set_major_locator(NullLocator())
savefig("filename.pdf", bbox_inches = 'tight',
pad_inches = 0)
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.
answered Dec 1 '14 at 11:45
Johannes S.Johannes S.
83672
83672
5
Finally something that works, thank you so much! By the way, in my case only the two lines usingset_major_locator
were necessary.
– Florian Brucker
Oct 28 '15 at 17:54
3
I've spent the last hour trying various things and could not get rid of a 1px white border. This was the only thing which worked - specifically thepad_inches=0
which other answers do not mention.
– Annan
May 16 '16 at 17:54
3
The only answer that actually worked!
– Sleepyhead
May 24 '16 at 8:18
7
pad_inches
helped me.
– Myles Baker
Aug 15 '16 at 4:56
3
matplotlib.ticker.NullLocator()
– Joop
Jun 14 '17 at 13:14
|
show 9 more comments
5
Finally something that works, thank you so much! By the way, in my case only the two lines usingset_major_locator
were necessary.
– Florian Brucker
Oct 28 '15 at 17:54
3
I've spent the last hour trying various things and could not get rid of a 1px white border. This was the only thing which worked - specifically thepad_inches=0
which other answers do not mention.
– Annan
May 16 '16 at 17:54
3
The only answer that actually worked!
– Sleepyhead
May 24 '16 at 8:18
7
pad_inches
helped me.
– Myles Baker
Aug 15 '16 at 4:56
3
matplotlib.ticker.NullLocator()
– Joop
Jun 14 '17 at 13:14
5
5
Finally something that works, thank you so much! By the way, in my case only the two lines using
set_major_locator
were necessary.– Florian Brucker
Oct 28 '15 at 17:54
Finally something that works, thank you so much! By the way, in my case only the two lines using
set_major_locator
were necessary.– Florian Brucker
Oct 28 '15 at 17:54
3
3
I've spent the last hour trying various things and could not get rid of a 1px white border. This was the only thing which worked - specifically the
pad_inches=0
which other answers do not mention.– Annan
May 16 '16 at 17:54
I've spent the last hour trying various things and could not get rid of a 1px white border. This was the only thing which worked - specifically the
pad_inches=0
which other answers do not mention.– Annan
May 16 '16 at 17:54
3
3
The only answer that actually worked!
– Sleepyhead
May 24 '16 at 8:18
The only answer that actually worked!
– Sleepyhead
May 24 '16 at 8:18
7
7
pad_inches
helped me.– Myles Baker
Aug 15 '16 at 4:56
pad_inches
helped me.– Myles Baker
Aug 15 '16 at 4:56
3
3
matplotlib.ticker.NullLocator()
– Joop
Jun 14 '17 at 13:14
matplotlib.ticker.NullLocator()
– Joop
Jun 14 '17 at 13:14
|
show 9 more comments
You can remove the white space padding by setting bbox_inches="tight"
in savefig
:
plt.savefig("test.png",bbox_inches='tight')
You'll have to put the argument to bbox_inches
as a string, perhaps this is why it didn't work earlier for you.
Possible duplicates:
Matplotlib plots: removing axis, legends and white spaces
How to set the margins for a matplotlib figure?
Reduce left and right margins in matplotlib plot
1
If you have multiple subplots and want to save each of them, you can use this withfig.savefig()
too. (plt.savefig()
will not work in that case.)
– Abhranil Das
Apr 21 '13 at 12:06
18
That's not quite right. When you use thatbbox_inches
option, there's another default that leaves some space. If you really want to get rid of everything, you need to also usepad_inches=0.0
. Of course, such tight padding frequently cuts off, e.g., exponents...
– Mike
Dec 19 '14 at 16:46
16
still some whitespace left...
– Sleepyhead
May 24 '16 at 8:15
4
To remove the black edge as well, you may need to setpad_inches=-0.1
– lenhhoxung
Oct 12 '17 at 14:09
3
This simply doesn't work, you still get whitespace around the figure. Setting the transparent option (as mentioned in some answers) doesn't really help either, the whitespace is still there, it's only transparent.
– BjornW
Apr 7 '18 at 10:50
|
show 4 more comments
You can remove the white space padding by setting bbox_inches="tight"
in savefig
:
plt.savefig("test.png",bbox_inches='tight')
You'll have to put the argument to bbox_inches
as a string, perhaps this is why it didn't work earlier for you.
Possible duplicates:
Matplotlib plots: removing axis, legends and white spaces
How to set the margins for a matplotlib figure?
Reduce left and right margins in matplotlib plot
1
If you have multiple subplots and want to save each of them, you can use this withfig.savefig()
too. (plt.savefig()
will not work in that case.)
– Abhranil Das
Apr 21 '13 at 12:06
18
That's not quite right. When you use thatbbox_inches
option, there's another default that leaves some space. If you really want to get rid of everything, you need to also usepad_inches=0.0
. Of course, such tight padding frequently cuts off, e.g., exponents...
– Mike
Dec 19 '14 at 16:46
16
still some whitespace left...
– Sleepyhead
May 24 '16 at 8:15
4
To remove the black edge as well, you may need to setpad_inches=-0.1
– lenhhoxung
Oct 12 '17 at 14:09
3
This simply doesn't work, you still get whitespace around the figure. Setting the transparent option (as mentioned in some answers) doesn't really help either, the whitespace is still there, it's only transparent.
– BjornW
Apr 7 '18 at 10:50
|
show 4 more comments
You can remove the white space padding by setting bbox_inches="tight"
in savefig
:
plt.savefig("test.png",bbox_inches='tight')
You'll have to put the argument to bbox_inches
as a string, perhaps this is why it didn't work earlier for you.
Possible duplicates:
Matplotlib plots: removing axis, legends and white spaces
How to set the margins for a matplotlib figure?
Reduce left and right margins in matplotlib plot
You can remove the white space padding by setting bbox_inches="tight"
in savefig
:
plt.savefig("test.png",bbox_inches='tight')
You'll have to put the argument to bbox_inches
as a string, perhaps this is why it didn't work earlier for you.
Possible duplicates:
Matplotlib plots: removing axis, legends and white spaces
How to set the margins for a matplotlib figure?
Reduce left and right margins in matplotlib plot
edited May 23 '17 at 12:26
Community♦
11
11
answered Aug 7 '12 at 13:39
HookedHooked
47k26136204
47k26136204
1
If you have multiple subplots and want to save each of them, you can use this withfig.savefig()
too. (plt.savefig()
will not work in that case.)
– Abhranil Das
Apr 21 '13 at 12:06
18
That's not quite right. When you use thatbbox_inches
option, there's another default that leaves some space. If you really want to get rid of everything, you need to also usepad_inches=0.0
. Of course, such tight padding frequently cuts off, e.g., exponents...
– Mike
Dec 19 '14 at 16:46
16
still some whitespace left...
– Sleepyhead
May 24 '16 at 8:15
4
To remove the black edge as well, you may need to setpad_inches=-0.1
– lenhhoxung
Oct 12 '17 at 14:09
3
This simply doesn't work, you still get whitespace around the figure. Setting the transparent option (as mentioned in some answers) doesn't really help either, the whitespace is still there, it's only transparent.
– BjornW
Apr 7 '18 at 10:50
|
show 4 more comments
1
If you have multiple subplots and want to save each of them, you can use this withfig.savefig()
too. (plt.savefig()
will not work in that case.)
– Abhranil Das
Apr 21 '13 at 12:06
18
That's not quite right. When you use thatbbox_inches
option, there's another default that leaves some space. If you really want to get rid of everything, you need to also usepad_inches=0.0
. Of course, such tight padding frequently cuts off, e.g., exponents...
– Mike
Dec 19 '14 at 16:46
16
still some whitespace left...
– Sleepyhead
May 24 '16 at 8:15
4
To remove the black edge as well, you may need to setpad_inches=-0.1
– lenhhoxung
Oct 12 '17 at 14:09
3
This simply doesn't work, you still get whitespace around the figure. Setting the transparent option (as mentioned in some answers) doesn't really help either, the whitespace is still there, it's only transparent.
– BjornW
Apr 7 '18 at 10:50
1
1
If you have multiple subplots and want to save each of them, you can use this with
fig.savefig()
too. (plt.savefig()
will not work in that case.)– Abhranil Das
Apr 21 '13 at 12:06
If you have multiple subplots and want to save each of them, you can use this with
fig.savefig()
too. (plt.savefig()
will not work in that case.)– Abhranil Das
Apr 21 '13 at 12:06
18
18
That's not quite right. When you use that
bbox_inches
option, there's another default that leaves some space. If you really want to get rid of everything, you need to also use pad_inches=0.0
. Of course, such tight padding frequently cuts off, e.g., exponents...– Mike
Dec 19 '14 at 16:46
That's not quite right. When you use that
bbox_inches
option, there's another default that leaves some space. If you really want to get rid of everything, you need to also use pad_inches=0.0
. Of course, such tight padding frequently cuts off, e.g., exponents...– Mike
Dec 19 '14 at 16:46
16
16
still some whitespace left...
– Sleepyhead
May 24 '16 at 8:15
still some whitespace left...
– Sleepyhead
May 24 '16 at 8:15
4
4
To remove the black edge as well, you may need to set
pad_inches=-0.1
– lenhhoxung
Oct 12 '17 at 14:09
To remove the black edge as well, you may need to set
pad_inches=-0.1
– lenhhoxung
Oct 12 '17 at 14:09
3
3
This simply doesn't work, you still get whitespace around the figure. Setting the transparent option (as mentioned in some answers) doesn't really help either, the whitespace is still there, it's only transparent.
– BjornW
Apr 7 '18 at 10:50
This simply doesn't work, you still get whitespace around the figure. Setting the transparent option (as mentioned in some answers) doesn't really help either, the whitespace is still there, it's only transparent.
– BjornW
Apr 7 '18 at 10:50
|
show 4 more comments
I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:
plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)
2
transparent=True
will make it seem like there's no problem but it will just hide white space, image dimensions won't be ok.
– Vlady Veselinov
Jul 28 '18 at 16:34
add a comment |
I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:
plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)
2
transparent=True
will make it seem like there's no problem but it will just hide white space, image dimensions won't be ok.
– Vlady Veselinov
Jul 28 '18 at 16:34
add a comment |
I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:
plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)
I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:
plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)
edited Sep 11 '17 at 15:25
mkl
54.5k1168146
54.5k1168146
answered Sep 11 '17 at 15:05
unclericounclerico
11712
11712
2
transparent=True
will make it seem like there's no problem but it will just hide white space, image dimensions won't be ok.
– Vlady Veselinov
Jul 28 '18 at 16:34
add a comment |
2
transparent=True
will make it seem like there's no problem but it will just hide white space, image dimensions won't be ok.
– Vlady Veselinov
Jul 28 '18 at 16:34
2
2
transparent=True
will make it seem like there's no problem but it will just hide white space, image dimensions won't be ok.– Vlady Veselinov
Jul 28 '18 at 16:34
transparent=True
will make it seem like there's no problem but it will just hide white space, image dimensions won't be ok.– Vlady Veselinov
Jul 28 '18 at 16:34
add a comment |
I found the following codes work perfectly for the job.
fig = plt.figure(figsize=[6,6])
ax = fig.add_subplot(111)
ax.imshow(data)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
plt.savefig('data.png', dpi=400, bbox_inches='tight',pad_inches=0)
2
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
– Tim Diekmann
May 24 '18 at 15:26
add a comment |
I found the following codes work perfectly for the job.
fig = plt.figure(figsize=[6,6])
ax = fig.add_subplot(111)
ax.imshow(data)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
plt.savefig('data.png', dpi=400, bbox_inches='tight',pad_inches=0)
2
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
– Tim Diekmann
May 24 '18 at 15:26
add a comment |
I found the following codes work perfectly for the job.
fig = plt.figure(figsize=[6,6])
ax = fig.add_subplot(111)
ax.imshow(data)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
plt.savefig('data.png', dpi=400, bbox_inches='tight',pad_inches=0)
I found the following codes work perfectly for the job.
fig = plt.figure(figsize=[6,6])
ax = fig.add_subplot(111)
ax.imshow(data)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
plt.savefig('data.png', dpi=400, bbox_inches='tight',pad_inches=0)
answered May 24 '18 at 15:16
Richard Yu LiuRichard Yu Liu
6113
6113
2
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
– Tim Diekmann
May 24 '18 at 15:26
add a comment |
2
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
– Tim Diekmann
May 24 '18 at 15:26
2
2
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
– Tim Diekmann
May 24 '18 at 15:26
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
– Tim Diekmann
May 24 '18 at 15:26
add a comment |
After trying the above answers with no success (and a slew of other stack posts) what finally worked for me was just
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig("myfig.pdf")
Importantly this does not include the bbox or padding arguments. For unclear reasons, when I had the bbox argument included in my savefig, my figure was shifted right and upwards off-center.
add a comment |
After trying the above answers with no success (and a slew of other stack posts) what finally worked for me was just
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig("myfig.pdf")
Importantly this does not include the bbox or padding arguments. For unclear reasons, when I had the bbox argument included in my savefig, my figure was shifted right and upwards off-center.
add a comment |
After trying the above answers with no success (and a slew of other stack posts) what finally worked for me was just
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig("myfig.pdf")
Importantly this does not include the bbox or padding arguments. For unclear reasons, when I had the bbox argument included in my savefig, my figure was shifted right and upwards off-center.
After trying the above answers with no success (and a slew of other stack posts) what finally worked for me was just
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig("myfig.pdf")
Importantly this does not include the bbox or padding arguments. For unclear reasons, when I had the bbox argument included in my savefig, my figure was shifted right and upwards off-center.
answered Nov 15 '18 at 0:19
SuaveSourisSuaveSouris
461712
461712
add a comment |
add a comment |
i followed this sequence and it worked like a charm.
plt.axis("off")
fig=plt.imshow(image array,interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('destination_path.pdf',bbox_inches='tight', pad_inches = 0, format='pdf', dpi=1200)
add a comment |
i followed this sequence and it worked like a charm.
plt.axis("off")
fig=plt.imshow(image array,interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('destination_path.pdf',bbox_inches='tight', pad_inches = 0, format='pdf', dpi=1200)
add a comment |
i followed this sequence and it worked like a charm.
plt.axis("off")
fig=plt.imshow(image array,interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('destination_path.pdf',bbox_inches='tight', pad_inches = 0, format='pdf', dpi=1200)
i followed this sequence and it worked like a charm.
plt.axis("off")
fig=plt.imshow(image array,interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('destination_path.pdf',bbox_inches='tight', pad_inches = 0, format='pdf', dpi=1200)
answered Nov 27 '18 at 13:06
KhanKhan
16215
16215
add a comment |
add a comment |
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')
add a comment |
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')
add a comment |
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 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')
answered Nov 28 '18 at 9:23
TomNorwayTomNorway
18712
18712
add a comment |
add a comment |
This works for me saving a numpy array plotted with imshow to file
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()
add a comment |
This works for me saving a numpy array plotted with imshow to file
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()
add a comment |
This works for me saving a numpy array plotted with imshow to file
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()
This works for me saving a numpy array plotted with imshow to file
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()
answered May 2 '18 at 1:52
Alejandro SazoAlejandro Sazo
4391020
4391020
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11837979%2fremoving-white-space-around-a-saved-image-in-matplotlib%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Possible duplicate of Saving a matplotlib/networkx figure without margins
– Joel
Oct 13 '15 at 10:03
What really worked for me was to crop the pdf using another tool, such as pdfcrop.
– toliveira
Jun 12 '18 at 11:33