Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: remove 3D plot's white spaces in mixed 2D/3D subplots

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

like image 282
Phyinmi Avatar asked Jul 05 '17 05:07

Phyinmi


People also ask

How do I reduce the gap between subplots?

We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.

How do I remove spaces between subplots in Python?

To remove the space between subplots in matplotlib, we can use GridSpec(3, 3) class and add axes as a subplot arrangement.

How do you stop subplots from overlapping?

Often you may use subplots to display multiple plots alongside each other in Matplotlib. Unfortunately, these subplots tend to overlap each other by default. The easiest way to resolve this issue is by using the Matplotlib tight_layout() function.


1 Answers

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.

like image 160
ImportanceOfBeingErnest Avatar answered Oct 12 '22 13:10

ImportanceOfBeingErnest