9

I am having trouble removing the excessive white spaces when mixing 2D and 3D subplots. For pure 3D subplots, I can adjust the region being plotted with fig.subplots_adjust() to remove the white spaces, see here.

However, the same trick doesn't work if this 3D image is inside a 2D subplots. I created the mixed subplots like the following:

import matplotlib.pyplot as plt    
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d

fig,axes = plt.subplots(2,2)
ax = axes.flat

for a in range(3):
    ax[a].plot(range(10),range(10))

ax[3].remove()
ax[3] = fig.add_subplot(224,projection='3d')

X, Y, Z = axes3d.get_test_data(0.03)
ax[3].plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.8,cmap=cm.coolwarm)

ax[3].set_xticklabels('')
ax[3].set_yticklabels('')
ax[3].set_zticklabels('')

fig.subplots_adjust(hspace=0,wspace=0)

Now the trick eg. fig.subplots_adjust(left=-0.01) will act on the 2D subplot's left edge, and the 3D subplots is not modified. Is there a way to completely remove the white spaces surrounding the 3D subplot? I also tried smaller ax.dist and it is not good if the 3D plot is longer in say z-direction.

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Phyinmi
  • 450
  • 7
  • 15

1 Answers1

8

There is no whitespace around the axes, it even overlaps the other subplots (their spines are hidden by the 3D axes).

What you want is to adjust the size of gray cube inside the axes. This can be done by changing the viewing distance to that cube.

E.g. ax[3].dist = 7

enter image description here

ax[3].dist = 9

enter image description here

The optimal distance depends of course on the viewing angle.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • I tried `ax.dist` before, but since the 3D subplot's grey cube is not a square, one of the side will have more spacing than the other. That's what I want to remove. In your `ax.dist=9` case, is it possible to remove spacing on the left, and then stretch the bottom edge down to mimic the aspect ratio? – Phyinmi Jul 06 '17 at 17:09
  • "*The dist attribute was deprecated*", [new method](https://stackoverflow.com/a/75146907/774575). – mins Mar 30 '23 at 10:55