Search code examples
matplotlibcolorbarscientific-notation

Colorbar scientific notation, change e^ to 10^


I am using scientific notation in a colorbar within a 2D plot. I want to write 10^{-3} instead of e-3. I tried to change that (see code below) but it does not work...

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker

x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)*0.001

x=x.reshape((10,10))

y=y.reshape((10,10))

z=z.reshape((10,10))

fig, ax = plt.subplots(figsize=(8,6))

cs = ax.contourf(x,y,z, 10)

plt.xticks(fontsize=16,rotation=0)
plt.yticks(fontsize=16,rotation=0)

cbar = plt.colorbar(cs,)
cbar.set_label("test",fontsize = 22)


cbar.formatter.set_scientific(True)
cbar.formatter.set_powerlimits((0, 0))
cbar.ax.tick_params(labelsize=16)
cbar.ax.yaxis.get_offset_text().set_fontsize(22)

cbar.ax.xaxis.major.formatter._useMathText = True

cbar.update_ticks()  

plt.savefig("test.png")

Solution

  • It seems you want a ScalarFormatter with mathtext in use.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.ticker
    
    x = np.tile(np.arange(10), 10).reshape((10,10))
    y = np.repeat(np.arange(10),10).reshape((10,10))
    z = np.sort(np.random.rand(100)*0.001).reshape((10,10))
    
    fig, ax = plt.subplots(figsize=(8,6))
    cs = ax.contourf(x,y,z, 10)
    
    fmt = matplotlib.ticker.ScalarFormatter(useMathText=True)
    fmt.set_powerlimits((0, 0))
    cbar = plt.colorbar(cs,format=fmt)
    
    plt.show()
    

    enter image description here