1

My question is very closely related to this questions and maybe to this one as well, although the solution of the latter didn't help me.

My code must generate a simple plot and save it:

def bizarre():
    x = np.arange(-5,5)
    y = np.arange(-10,10)
    xc,yc = np.meshgrid(x,y)
    zc = np.random.randint(-1,2,size=xc.shape)

    plt.figure()
    m = plt.pcolormesh(xc, yc, zc, shading='nearest', cmap='coolwarm', 
                       edgecolors='gray', linewidths=1, vmin=-1, vmax=1,
                       in_layout=False,)
    plt.colorbar(m)
    ax = plt.gca()
    ax.set_aspect('equal')
    plt.tight_layout()
    plt.savefig('bizzare.png', dpi=200)

bizarre()  # saves a figure with bizarre size

The function works perfectly fine and generates something like this in a Jupyter cell: enter image description here

Yet, for some mysterious reason, I get blank space on the left side of the saved figure. Something like this:

enter image description here

I'm genuinely interested to know why is that? Thanks.

arash
  • 161
  • 13
  • 2
    The default Jupiyter backend is “inline” and it saves figures with `savefig(…, bbox_inches=‘tight’)` which trims any white space. Shen you save without this option, you still get the white space. – Jody Klymak Jul 11 '21 at 14:36
  • Thanks @JodyKlymak. Exactly explains it. Should be the answer. – arash Jul 11 '21 at 15:56
  • Also note that `ax.set_aspect('equal')` either needs a narrower image, or needs whitespace to avoid the plot being stretched. – JohanC Jul 11 '21 at 17:21
  • @JohanC Does it mean that `bbox_inches` is designed to overwrite such whitespaces? – arash Jul 14 '21 at 14:30
  • 1
    `plt.savefig(..., bbox_inches='tight')` is supposed to remove superfluous whitespace near the borders. (To display a plot in a Jupyter notebook. `bbox_inches='tight'` is usually applied automatically.) – JohanC Jul 14 '21 at 20:39

0 Answers0