Search code examples
pythonmatplotlib3dgridlines

Extending gridlines in a 3d matplotlib plot


Is there any way to extend gridlines into the data area of a 3d plot?

I have this plot, and all of the plots are at 1 for the z-axis (confirmed by checking the array values), but this doesn't look obvious to me. I'm hoping that adding internal gridlines will help to clarify it. I generated it with this code:

fig = plt.figure(figsize = (10,10))
ax = plt.axes(projection ='3d')
x, y, z = np.array(list1), np.array(list2), np.array(list3) 
c = x+y
ax.scatter(x, y, z, c=c)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title(f'Title')
plt.show()

enter image description here

Thanks!


Solution

  • Option 1

    • If all the points are at a single Z value, then only plot a single plane
    import matplotlib.pyplot as plt
    import numpy as np
    
    # test data
    np.random.seed(365)
    x, y = np.random.randint(2500, 20000, size=(7, )), np.random.randint(0, 1600, size=(7, ))
    
    fig, ax = plt.subplots(figsize=(6, 6))
    ax.scatter(x=x, y=y)
    ax.set(title='Plane at Z=1')
    

    enter image description here

    Option 2

    • Plot lines at the axis ticks
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure(figsize=(10, 10))
    ax = plt.axes(projection='3d')
    
    # test data
    np.random.seed(365)
    x, y, z = np.random.randint(2500, 20000, size=(7, )), np.random.randint(0, 1600, size=(7, )), np.ones(7) 
    
    c = x+y
    ax.scatter(x, y, z, c=c)
    
    # get the x and y tick locations
    x_ticks = ax.get_xticks()
    y_ticks = ax.get_yticks()
    
    # add lines
    for y1 in y_ticks:
        x1, x2 = x_ticks[0], x_ticks[-1]
        ax.plot([x1, x2], [y1, y1], [1, 1], color='lightgray')
    for x1 in x_ticks:
        y1, y2 = y_ticks[0], y_ticks[-1]
        ax.plot([x1, x1], [y1, y2], [1, 1], color='lightgray')
        
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    ax.set_title(f'Title')
    plt.show()
    

    enter image description here

    enter image description here