Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving plot from ipython notebook produces a cut image

I am plotting a plot with 2 ylabels using ipython notebook and the image looks good when visualized inside the notebook.

Here is how I do it:

import matplotlib.pyplot as plt 

fig, ax1 = plt.subplots()
plt.title('TITLE')
plt.xlabel('X')

plt.plot(x, y1, '-', color='blue', label='SNR')
ax1.set_ylabel('y1', color='blue')
for tl in ax1.get_yticklabels():
    tl.set_color('blue')

ax2 = ax1.twinx()
plt.plot(x, y2, '--', color='red', label='Ngal')
ax2.set_ylabel('y2', color='red')
for tl in ax2.get_yticklabels():
    tl.set_color('red')

The problem is that when I try to save it with the command

plt.savefig('output.png', dpi=300)

since the output will be an image which is cut on the right side: basically I don't see the right ylabel if the right numbers are large.

like image 860
Alberto Avatar asked Sep 28 '22 05:09

Alberto


1 Answers

By default, matplotlib leaves very little room for x and y axis labels and tick labels, therefore you need to adjust the figure to include more padding. Fortunately this could not be easier to do. Before you call savefig, you can call call

fig.tight_layout()
plt.savefig('output.png', dpi=300)

Alternatively, you can pass bbox_inches='tight' to savefig which will also adjust the figure to include all of the x and y labels

plt.savefig('output.png', dpi=300, bbox_inches='tight')
like image 183
Kyle Avatar answered Oct 28 '22 15:10

Kyle