Scientific notation colorbar in matplotlib

前端 未结 3 1607
名媛妹妹
名媛妹妹 2020-12-07 16:46

I am trying to put a colorbar to my image using matplotlib. The issue comes when I try to force the ticklabels to be written in scientific notation. How can I force the scie

相关标签:
3条回答
  • 2020-12-07 17:23

    You could use colorbar's format parameter:

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.ticker as ticker
    
    img = np.random.randn(300,300)
    myplot = plt.imshow(img)
    
    def fmt(x, pos):
        a, b = '{:.2e}'.format(x).split('e')
        b = int(b)
        return r'${} \times 10^{{{}}}$'.format(a, b)
    
    plt.colorbar(myplot, format=ticker.FuncFormatter(fmt))
    plt.show()
    

    enter image description here

    0 讨论(0)
  • 2020-12-07 17:32

    You can specify the format of the colorbar ticks as follows:

    pl.colorbar(myplot, format='%.0e')
    
    0 讨论(0)
  • 2020-12-07 17:48

    There is a more straightforward (but less customizable) way to get scientific notation in a ColorBar without the %.0e formatting.

    Create your ColorBar:

    cbar = plt.colorbar()
    

    And call the formatter:

    cbar.formatter.set_powerlimits((0, 0))
    

    This will make the ColorBar use scientific notation. See the example figure below to see how the ColorBar will look.

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