Search code examples
pythonmatplotlibsurface

The plot_surface does not appear in my graph


I want to create a bezier surface but the surfacce does not appear. The odd thing is that when I plot the control points instead of the bezier points it works. Here is my code :

import numpy as np
import matplotlib.pyplot as plt

n = 10 #grid size
X = np.arange(0, 1, 1/n)
Y = np.arange(0, 1, 1/n)
X, Y = np.meshgrid(X,Y)
Z = np.zeros((n,n))
#here I try to create random continuously control points to have a nice surface
Z[0] = np.random.random()
for i in range(n - 1):
    Z[i + 1] = Z[i] * (1 + 0.1 * (np.random.normal() * 2 - 1))
for i in range(n):
    for j in range(n):
        Z[i][j] += 0.05 * Z[i][j] * (np.random.normal() * 2 - 1)

d = 10 #number of divisions (one point per control point

u, v = np.linspace(0, 1, d), np.linspace(0, 1, d) #variables

binome = lambda n, k : np.math.factorial(n) / (np.math.factorial(k) * np.math.factorial(n - k))
bernstein = lambda n, k, t : binome(n, k) * t**k * (1 - t)**(n-k)

def bezier(X,Y,Z):
    xBezier = np.zeros((d, d))
    yBezier = np.zeros((d, d))
    zBezier = np.zeros((d, d))

    for i in range(n):
        for j in range(n): #calcul de la surface
            xBezier += bernstein(n - 1, i, u) * bernstein(n - 1, j, v) * X[i, j]
            yBezier += bernstein(n - 1, i, u) * bernstein(n - 1, j, v) * Y[i, j]
            zBezier += bernstein(n - 1, i, u) * bernstein(n - 1, j, v) * Z[i, j]

    return(xBezier, yBezier, zBezier)

xBezier, yBezier, zBezier = bezier(X, Y, Z)

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_surface(xBezier, yBezier, zBezier, cmap=plt.cm.Blues)
ax.scatter(X, Y, Z, edgecolors = 'face')
plt.show()

Any idea?


Solution

  • When you run plot_surface, x should be the x axis repeated for each y, and y should be the y axis repeated for each x. I replaced yBezier with its transpose yBezier.T. (I also lowered the minimum colourmap value to bring out the colour at the lower end).

    enter image description here

    ...
    ax.plot_surface(xBezier, yBezier.T, zBezier, cmap=plt.cm.Blues, vmin=zBezier.min() * 0.8)
    ax.scatter(X, Y, Z, edgecolors = 'face', color='tab:red')
    ...