Anirban Chakraborty
Anirban Chakraborty

Reputation: 781

Matplotlib 3d surface plot showing values outside of axis limits

In matplotlib 3d-plotting plot_surface even when the x, y and z axis limits are set to be >=0 the negative z-portion of the surface is still getting plotted. The same does not happen for 2d plots- if out of 20 data points provided as input for plotting, 10 fall outside the axis limits, say first-quadrant, they simply do not get displayed in the plot.

Please see the below code and corresponding plot as an evidence (code run in Jupyter notebook) -

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import cm
%matplotlib notebook

x = np.linspace(0,1.5,100)
y = np.linspace(0,1.5,100)
X,Y = np.meshgrid(x,y)
Z = 1-X-Y
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
surf = ax.plot_surface(X,Y,Z,cmap=cm.coolwarm)
ax.set_xlim(0,1.5)
ax.set_ylim(0,1.5)
ax.set_zlim(0,3)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
fig.colorbar(surf, shrink=0.5, aspect=5)
fig.savefig('Question10Fig')

Above plot

The existence of the blue colour along with the colour-bar alongside makes it evident that z<0 values are present in the plot. Why is that so?

Upvotes: 3

Views: 4194

Answers (2)

Chenchow Tsu
Chenchow Tsu

Reputation: 15

Add following code:

z[z < 0] = np.nan

just using set_zlim is not enough.

Upvotes: 0

Tobias Windisch
Tobias Windisch

Reputation: 1039

That seems to origin from

ax.set_zlim(0,3)

Removing this line, the figure looks good to me. That seems to be a problem in matplotlib (see also this post).

Upvotes: 1

Related Questions