Reputation: 2486
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")
Upvotes: 35
Views: 57735
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
Reputation: 1
Comment out plt.show()
and instead call plt.savefig('abc.png')
.
Upvotes: 0
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)
Upvotes: 3
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
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
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
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")
Upvotes: 10