Home > database >  Matplotlib - Surface incorrectly plotted on top of Lines
Matplotlib - Surface incorrectly plotted on top of Lines

Time:12-03

I'm trying to have a graph with plotted lines above a displayed image surface, however any lines drawn appear underneath the image. I'm using plot_surface to display the image as in the example function display_image_on_z_plane below. There should be a line across the X axis here.

Edit: I have tried placing the call before/after the drawing of the line. Using Matplotlib 3.5.0. Plotting a surface above a surface seems to work fine, ala enter image description here

    import matplotlib.pyplot as plt
    from matplotlib import cm
    import numpy as np
    import cv2
    
    def display_image_on_z_plane(image, ax, z_level):
        step_x, step_y = 10. / image.shape[0], 10. / image.shape[1]
    
        bg_X = np.arange(-5., 5., step_x)
        bg_Y = np.arange(-5., 5., step_y)
    
        bg_X, bg_Y = np.meshgrid(bg_X, bg_Y)
    
        ax.plot_surface(bg_X, bg_Y, np.atleast_2d(z_level), rstride=2, cstride=2, facecolors=image, shade=False)
    
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    
    # Display Random Graph
    
    X = [-5, 5]
    Y = [0, 0]
    Z = [0, 0]
    ax.plot(X, Y, Z)
    
    
    image = cv2.imread("Lenna_(test_image).png")
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = image.astype(np.float32) / 255.0
    image = cv2.flip(image, 0)
    
    display_image_on_z_plane(image, ax, -0.01)
    ax.set_zlim(-0.05, 0.3)
    plt.show()

CodePudding user response:

Apparently this is due to the way Matplotlib works. You have to manually specify the z order.

Here is my updated code example:

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import cv2

def display_image_on_z_plane(image, ax, z_level):
    step_x, step_y = 10. / image.shape[0], 10. / image.shape[1]

    bg_X = np.arange(-5., 5., step_x)
    bg_Y = np.arange(-5., 5., step_y)

    bg_X, bg_Y = np.meshgrid(bg_X, bg_Y)

    ax.plot_surface(bg_X, bg_Y, np.atleast_2d(z_level), rstride=2, cstride=2, facecolors=image, shade=False, zorder=0)

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

image = cv2.imread("Lenna_(test_image).png")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = image.astype(np.float32) / 255.0
image = cv2.flip(image, 0)

display_image_on_z_plane(image, ax, -0.01)

# Display Random Graph

X = [-5, 5]
Y = [0, 0]
Z = [0, 0]
ax.plot(X, Y, Z, zorder=10)


ax.set_zlim(-0.05, 0.3)
plt.show()
  • Related