Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib with annotation cut off from the saved figure

I'm using matplotlib to draw something figure while using annotations. The problem I experienced is that the annotation (which is outside the plotting area) is cut off from the saved picture, as shown in the following figure.

figure with annotations cut off

This following figure is the one I want:

The desired picture

Anybody knows how to solve this problem? I noticed people suggest using plt.tight_plot() or fig.autolayout in rcParams, but that doesn't seem to work. Below is the code for producing the figure.

fig, ax = plt.subplots() ax.set_xlim([-0.02,1.1]) ax.set_ylim([-0.02,1.1])  ax.plot([0,0,0,0.5,0.5,0.5,1,1,1], [0,0.5,1,0,0.5,1,0,0.5,1], 'go')  ax.annotate("Digit 2",             xy=(0.5, -0.1), xycoords='data',             xytext=(0.5, -0.3), textcoords='data',             arrowprops=dict(arrowstyle="->",                             connectionstyle="arc3"),              annotation_clip=False,              fontsize = 12,              ha='center',             )  ax.annotate("Level 2",             xy=(-0.1, 1), xycoords='data',             xytext=(-0.35, 1), textcoords='data',             arrowprops=dict(arrowstyle="->",                             connectionstyle="arc3"),                     annotation_clip=False,                     fontsize = 12,                     va='center',             )  plt.savefig('sample.png', dpi = 300) 
like image 272
user3821012 Avatar asked Apr 27 '15 16:04

user3821012


People also ask

How do I save a figure in matplotlib?

Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.

How do I stop matplotlib from overlapping text?

To avoid overlapping of labels and autopct in a matplotlib pie chart, we can follow label as a legend, using legend() method.

Does matplotlib overwrite Savefig?

Matplotlib Savefig will NOT overwrite old files.


1 Answers

Save figure with the bbox_inches argument

plt.savefig('sample.png', bbox_inches="tight") 
like image 188
ODiogoSilva Avatar answered Sep 19 '22 08:09

ODiogoSilva