# surface plots in matplotlib

### Question

I have a list of 3-tuples representing a set of points in 3D space. I want to plot a surface that covers all these points. The plot_surface function in the mplot3d package requires as arguments X,Y and Z which are 2d arrays. Is plot_surface the right function to plot surface and how do I transform my data in to the required format ?

`data = [(x1,y1,z1),(x2,y2,z2),.....,(xn,yn,zn)]`

1
86
2/7/2012 4:02:45 AM

For surfaces it's a bit different than a list of 3-tuples, you should pass in a grid for the domain in 2d arrays.

If all you have is a list of 3d points, rather than some function `f(x, y) -> z`, then you will have a problem because there are multiple ways to triangulate that 3d point cloud into a surface.

Here's a smooth surface example:

``````import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# Axes3D import has side effects, it enables using projection='3d' in add_subplot
import matplotlib.pyplot as plt
import random

def fun(x, y):
return x**2 + y

fig = plt.figure()
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array(fun(np.ravel(X), np.ravel(Y)))
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
``````

101
4/2/2019 7:30:15 PM

You can read data direct from some file and plot

``````from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from sys import argv

fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.savefig('teste.pdf')
plt.show()
``````

If necessary you can pass vmin and vmax to define the colorbar range, e.g.

``````surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1, vmin=0, vmax=2000)
``````

# Bonus Section

I was wondering how to do some interactive plots, in this case with artificial data

``````from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import Image

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

def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))

def plot(i):

fig = plt.figure()
ax = plt.axes(projection='3d')

theta = 2 * np.pi * np.random.random(1000)
r = i * np.random.random(1000)
x = np.ravel(r * np.sin(theta))
y = np.ravel(r * np.cos(theta))
z = f(x, y)

ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none')
fig.tight_layout()

interactive_plot = interactive(plot, i=(2, 10))
interactive_plot
``````