How to make a 3d matlibplot not show masked values

前端 未结 1 745
失恋的感觉
失恋的感觉 2020-12-20 23:20

The diagram should only show the masked values. As in the (manipulated) figure on the right side.

Default shows all values. In 2d diagramms there is no problem.

相关标签:
1条回答
  • 2020-12-21 00:24

    The bad news is that it seems that plot_surface() just ignores masks. In fact there is an open issue about it.

    However, here they point out a workaround that although it's far from perfect it may allow you get some acceptable results. The key issue is that NaN values will not be plotted, so you need to 'mask' the values that you don't want to plot as np.nan.

    Your example code would become something like this:

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    import numpy as np
    
    
    Z = np.array([
        [ 1, 1, 1, 1, 1, ],
        [ 1, 1, 1, 1, 1, ],
        [ 1, 1, 1, 1, 1, ],
        [ 1, 1, 1, 1, 1, ],
        [ 1, 1, 1, 1, 1, ],
        ])
    
    x, y = Z.shape
    
    xs = np.arange(x)
    ys = np.arange(y)
    X, Y = np.meshgrid(xs, ys)
    
    
    R = np.where(X>=Y, Z, np.nan)
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(X, Y, R, rstride=1, linewidth=0)
    
    fig.show()
    

    *I had to add the rstride=1 argument to the plot_surface call; otherwise I get a segmentation fault... o_O

    And here's the result:

    3d matplotlib surface with masked values

    0 讨论(0)
提交回复
热议问题