Gaven
Gaven

Reputation: 1087

Matplotlib - 3D surface plot disappears when cmap colors are specified

I am writing a script that generates 3D plots from an initial set of x/y values that are not a mesh grid. The script runs well and converts the data into a mesh grid and plots it fine but when I specify a cmap color the plot disappears. Why would this happen?

code:

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = []
y = []
rlim = -4
llim = 4
increment = np.absolute((llim-rlim)*5)
linespace = np.array(np.linspace(rlim,llim,increment, endpoint = False))

for val in linespace:
    for val1 in linespace:
        x.append(val)
        y.append(val1)

x = np.array(x) 
y = np.array(y) 
z = np.array(np.sin(np.sqrt(np.power(x,2)+np.power(y,2)))/np.sqrt(np.power(x,2)+np.power(y,2)))

rows = len(np.unique(x[~pd.isnull(x)]))
array_size = len(x)
columns = int(array_size/rows)

X = np.reshape(x, (rows, columns))
Y = np.reshape(y, (rows, columns))
Z = np.reshape(z, (rows, columns))

ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                 cmap = 'Blues', edgecolor='none')
plt.show()

This yieldsenter image description here

However if all I do is delete the cmap entry in ax.plot_surface I ge the following:

enter image description here

Why simply adding a cmap delete the plot?

Upvotes: 1

Views: 453

Answers (1)

David Kaftan
David Kaftan

Reputation: 2174

Matplotlib is having a hard time scaling your colormap with NaNs in the Z matrix. I didn't look too close at your function, but it seems like you will get a NaN at the origin (0,0), and it looks like 1 is a reasonable replacement. Therefore, right after Z = np.reshape(z, (rows, columns)) I added Z[np.isnan(Z)] = 1., resulting in the following pretty graph: enter image description here

Upvotes: 1

Related Questions