Colorbar for matplotlib plot_surface using facecolors

前端 未结 1 1128
后悔当初
后悔当初 2020-12-07 03:28

I\'m trying to plot in 3D colouring the surface with predefined colours using facecolors. The problem here is that cm.ScalarMappable normalizes surface V<

相关标签:
1条回答
  • 2020-12-07 04:11

    Your plot is correct, although you might simplify the normalization using a matplotlib.colors.Normalize instance.

    norm = matplotlib.colors.Normalize(vmin=V.min().min(), vmax=V.max().max())
    ax.plot_surface(X, Y, Z, facecolors=plt.cm.jet(norm(V)))
    m = cm.ScalarMappable(cmap=plt.cm.jet, norm=norm)
    m.set_array([])
    plt.colorbar(m)
    

    The point why you don't see the maximum value of 10.15 on the grid, is a different one:

    When having N points along one dimension, the plot has (N-1) faces. That means that the last row and column of the input color array are simply not plotted.

    This can be seen in the following picture, where a 3x3 matrix is plotted, resulting in 2x2 faces. They are colorized according to the respective values in a color array, such that the first face has the color given by the first element in the array etc. For the last elements there is no face to color left.

    Code to reproduce this plot:

    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    import matplotlib.colors
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    x = np.arange(3)
    X,Y = np.meshgrid(x,x)
    Z = np.ones_like(X)
    
    V = np.array([[3,2,2],[1,0,3],[2,1,0]])
    
    norm = matplotlib.colors.Normalize(vmin=0, vmax=3)
    ax.plot_surface(X, Y, Z, facecolors=plt.cm.jet(norm(V)), shade=False)
    
    m = cm.ScalarMappable(cmap=plt.cm.jet, norm=norm)
    m.set_array([])
    plt.colorbar(m)
    
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    
    plt.show()
    
    0 讨论(0)
提交回复
热议问题