Richard Todd
Richard Todd

Reputation: 2486

Matplotlib savefig does not save axes

I'm trying to save a figure that works fine in IPython inline but does not save the figure to disk with the axes and titles included.

I am using TKAgg backend by default in matplotlibrc.

Any ideas what might be going wrong here? I have clearly set the xlabel and the tick marks work correctly in IPython inline plot.

import matplotlib.pylab as plt  
x = [1,2,3,3]
y = map(lambda(x): x * 2, x)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.set_title("bleh")
ax.set_xlabel("xlabel")
ax.plot(x, y, 'r--')
fig.savefig("fig.png")

Savefig image without axes labels

Upvotes: 35

Views: 57735

Answers (7)

Maya Petranova
Maya Petranova

Reputation: 390

Defining fig = plt.figure(figsize=(15,10)) at the beginning, saving the file as .jpg, and setting bbox_inches='tight' solved the issue for me.

plt.savefig('filename.jpg',bbox_inches='tight', dpi=150)

bbox_inches='tight' seems to fix cropping issues but it didn't work for .png.

Upvotes: 29

Vijendra Kotian
Vijendra Kotian

Reputation: 1

Comment out plt.show() and instead call plt.savefig('abc.png').

Upvotes: 0

Noor Alam
Noor Alam

Reputation: 31

I was using Jupyter Notebook and Just change .png to .jpg and my problem is solved now Here is my code:

# changing the size of figure to 2X2
plt.figure(dpi=100, figsize=(15, 10))
plt.grid()
#display(plt.plot(year1, ratio1))
x = np.arange(1900, 2020, 5)
plt.xticks(x)
plt.title(ttile)
plt.xlabel('Year')
plt.ylabel('Ratio')
plt.plot(year,ratio)
plt.savefig('books_read.jpg', dpi = 300)

Saved Image from the Code

Upvotes: 3

srinivas kumar
srinivas kumar

Reputation: 423

I was able to solve the issue (in visual studio code jupyter extension) by changing the format from 'png' to 'jpg', along with the parameter 'plt.subplots(tight_layout=True)'.

Upvotes: 4

mousomer
mousomer

Reputation: 2838

Could be facecolor. I work in jupyter lab, and the facecolor default is set to black, so you don't see the axes, even though they are being drawn.

fig = plt.figure(facecolor=(1, 1, 1))

sets the background color to white.

Upvotes: 13

VictorGGl
VictorGGl

Reputation: 1916

I was having the same problem using Jupyter notebook and the command: %matplotlib notebook. The figure showed correctly in the notebook but didn't print axis and titles when saved with fig.savefig(). I changed %matplotlib notebook to %matplotlib inline and that solved the problem.

Upvotes: 5

Molly
Molly

Reputation: 13610

You are setting the axis to start at the very bottom left of the figure and to fill up the entire thing. There's no room for the axis labels or the title. Try this:

import matplotlib.pylab as plt  
x = [1,2,3,3]
y = map(lambda(x): x * 2, x)
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.75,0.75]) # axis starts at 0.1, 0.1
ax.set_title("bleh")
ax.set_xlabel("xlabel")
ax.plot(x, y, 'r--')
fig.savefig("fig.png")

plot with axis showing

Upvotes: 10

Related Questions