5

I am trying to make a simple 3D surface plot with matplotlib but the plot does not show at the end; I only get empty 3D axes.

Here is what I did:

from mpl_toolkits.mplot3d import Axes3D

x = np.arange(1, 100, 1)
y = np.arange(1, 100, 1)
z = np.arange(1, 100, 1)

fig = figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, rstride=5, cstride=5) 
show()

...and I get this: enter image description here

Any suggestions?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Labibah
  • 5,371
  • 6
  • 25
  • 23
  • Have a look at these related/similar/duplicate posts: http://stackoverflow.com/q/3012783/3585557, http://stackoverflow.com/q/9170838/3585557, http://stackoverflow.com/q/12423601/3585557, http://stackoverflow.com/q/21161884/3585557, http://stackoverflow.com/q/26074542/3585557, http://stackoverflow.com/q/28389606/3585557 – Steven C. Howell May 30 '15 at 12:53

2 Answers2

2
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
from scipy.interpolate import griddata

x= np.arange(1, 100, 1)
y= np.arange(1, 100, 1)
z= np.arange(1, 100, 1)
fig = plt.figure()
ax = fig.gca(projection='3d')
xi = np.linspace(x.min(), x.max(), 50)
yi = np.linspace(y.min(), y.max(), 50)
zi = griddata((x, y), z, (xi[None, :], yi[:, None]), method='nearest')    # create a uniform spaced grid
xig, yig = np.meshgrid(xi, yi)
surf = ax.plot_wireframe(X=xig, Y=yig, Z=zi, rstride=5, cstride=3, linewidth=1)   # 3d plot
plt.show()

enter image description here

Kirubaharan J
  • 2,255
  • 16
  • 23
1

You are not plotting a surface: x, y and z needs to be 2D arrays. Look at this example: http://matplotlib.org/examples/mplot3d/surface3d_demo.html.

Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
  • 1
    Thanks! but it seems that Z must be a function of X and Y. What if the three of them are independent variables? – Labibah Apr 09 '15 at 20:58
  • 4
    Z can be independent of X and Y. That does not prevent you from plotting them. For example, `X = np.arange(-5,5,0.25); X,Y = np.meshgrid(X,X); Z = np.random.random(X.shape);`. However, X, Y and Z must have the same size. – Julien Spronck Apr 09 '15 at 21:04
  • OK. You're right. I think surface plots are not the ideal way to show my data. Probably because the variables are independent, the figure came out looking weird. – Labibah Apr 09 '15 at 21:29
  • Do you still know your final code Libabah? – Jorrick Sleijster Oct 06 '16 at 07:39