7

I'm having an issue with setting limits for my 3d plots in matplotlib; I'm finding that no matter how I set my limits for the x,y, and z axes, the plotting routine for 3dplots adds an extra buffer.

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt

fig = plt.figure() 
ax = fig.add_subplot(111,projection='3d') 
ax.axes.set_xlim3d(left=0, right=10) 
ax.axes.set_ylim3d(bottom=0, top=10) 
ax.axes.set_zlim3d(bottom=0, top=10) 
plt.show()

This produces the following plot:

3d axes image

As you can see, the limits are supposed to be at x, y, z = {0, 10} however the 3D plotting always adds a little bit of a buffer to each edge. Does anyone know a way to turn this effect off?

I've also used plt.xlims(); and ax.axes.set_xlims() but they produce the same effect.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
aarogers
  • 71
  • 1
  • 1
  • 2

1 Answers1

9

I think this is deliberate (see e.g. this), if you try plotting ax.axes.set_xlim3d(left=0.000001, right=9.9999999) then you get no 0 or 10 displayed on your figure.

enter image description here

Even making the numbers as arbitrarily close as possible doesn't work, e.g.

eps = 1e-16
ax.axes.set_xlim3d(left=0.-eps, right=10+eps)
ax.axes.set_ylim3d(bottom=0.-eps, top=10+eps) 
ax.axes.set_zlim3d(bottom=0.-eps, top=10+eps) 

The best solution I've found is to set the ticks manually and then slightly scale so the overlap is hidden.

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt

fig = plt.figure() 
ax = fig.add_subplot(111,projection='3d') 

ax.set_xticks([0,2,4,6,8,10])
ax.set_yticks([0,2,4,6,8,10])
ax.set_zticks([0,2,4,6,8,10])

ax.axes.set_xlim3d(left=0.2, right=9.8) 
ax.axes.set_ylim3d(bottom=0.2, top=9.8) 
ax.axes.set_zlim3d(bottom=0.2, top=9.8) 

plt.show()

This gives,

enter image description here

This is pretty hacky but could be made more general (and I always end up setting ticks manually for publication quality figures). Alternatively, it may be better to turn off the lowest grid line or hide the grid...

Ed Smith
  • 12,716
  • 2
  • 43
  • 55