Python matplotlib colorbar scientific notation base

前端 未结 2 1895
广开言路
广开言路 2020-12-09 11:17

I am trying to customise a colorbar on my matpllotlib contourf plots. Whilst I am able to use scientific notation I am trying to change the base of the notation - essentiall

2条回答
  •  佛祖请我去吃肉
    2020-12-09 12:11

    Similar to what @ImportanceOfBeingErnes described, you could use a FuncFormatter (docs) to which you just pass a function to determine the tick labels. This removes the auto generation of the 1e-2 header for your colorbar, but I imagine you can manually add that back in (I had trouble doing it, though was able to add it on the side). Using a FuncFormatter, you can just generate string tick values which has the advantage of not having to accept the way python thinks a number should be displayed.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.ticker as tk
    
    z = (np.random.random((10,10)) - 0.5) * 0.2
    
    levels = list(np.linspace(-.1,.1,9))
    
    fig, ax = plt.subplots()
    plot = ax.contourf(z, levels=levels)
    
    def my_func(x, pos):
        label = levels[pos]
        return str(label*100)
    
    fmt1 = tk.FuncFormatter(my_func)
    
    cbar = fig.colorbar(plot, format=fmt1)
    cbar.set_label("1e-2")
    
    plt.show()
    

    This will generate a plot which looks like this.

提交回复
热议问题