Matplotlib colorbar: how to manually set the intervals?

后端 未结 1 595
南方客
南方客 2021-01-17 03:01

I am using the following snippet to create a custom colorbar:

import pylab as pl
import numpy as np

a = np.array([[0,10000,100000,400000,500000]])
pl.figure         


        
相关标签:
1条回答
  • 2021-01-17 03:16

    As can be seen when not turning the axes invisible, the colorbar is correctly representing the color of the data in the image.

    If this is not what you want you should start by establishing how the data is represented in the image. Introducing a Normalization for the data to the colormap range is usually the way this is accomplished. Here a BoundaryNorm makes sense.

    import matplotlib.pyplot as plt
    import matplotlib.colors
    import numpy as np
    
    a = np.array([[0,10000,100000,400000,500000]])
    plt.figure(figsize=(4, 2.5))
    
    mycmap = matplotlib.colors.ListedColormap(['yellow','orange','red','darkred'])
    norm = matplotlib.colors.BoundaryNorm(a[0], len(a[0])-1)
    img = plt.imshow(a, cmap=mycmap, norm=norm)
    cax = plt.axes([0.1, 0.1, 0.8, 0.1])
    cbar=plt.colorbar(orientation='horizontal', cax=cax,spacing='proportional');
    
    plt.show()
    

    This now gives a meaningful representation with ticks at the edges of the colorranges.

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