matplotlib examples‎ > ‎Posts‎ > ‎

Clip 3D array points outside of axes

posted Jul 24, 2012, 6:14 AM by Mart Objartel   [ updated Jul 24, 2012, 6:45 AM ]
Issue:

While plotting a matplotlib 3D plot, if you set axis limits to be lesser than the the maximum range of the array.

The array values are plotted outside the axis area.

Example:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *

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

X = [-10, 3, 4, 5, 10]
Y = [100, 150, 250, 320, 400]
Z = [12, 23, 33, 44, 52]

ax.plot(X,Y,Z, ls="None", marker="o")

ax.set_xlabel("X")


plt.show()

Now when setting limits for X axis from
-5 to 5, data points outiside the axis are still plotted.
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *


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

X = [-10, 3, 4, 5, 10]
Y = [100, 150, 250, 320, 400]
Z = [12, 23, 33, 44, 52]


ax.plot(X,Y,Z, ls="None", marker="o")

ax.set_xlim3d(-5, 5)
ax.set_xlabel("X")


plt.show()

One possible way to get rid of these data points is to replace them with NaN, for example useing some simple "if logic". NB, for some reason does not work with scatter.

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *


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

X = [-10, 3, 4, 5, 10]
Y = [100, 150, 250, 320, 400]
Z = [12, 23, 33, 44, 52]

for i in np.arange(len(X)):
    if X[i] < -5:
        X[i] = NaN
        Y[i] = NaN
        Z[i] = NaN
    elif X[i] > 5:
        X[i] = NaN
        Y[i] = NaN
        Z[i] = NaN
    else:
        pass


ax.plot(X,Y,Z, ls="None", marker="o")

ax.set_xlim3d(-5, 5)
ax.set_xlabel("X")


plt.show()

Same can be done with wireframes or surfaces. For example one would like to get rid of all the wireframe bellow 0 in Z-axis:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.1)
           
ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
           
ax.set_zlim3d(0, 80)
plt.show()

Solution is similar to previous.

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.1)

for i in np.arange(len(X)):
    for j in np.arange(len(Y)):
        if Z[j,i] < 0:
            Z[j,i] = NaN
        else:
            pass
           
ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
           
ax.set_zlim3d(0, 80)
plt.show()


Comments