Search code examples
pythonmatplotlibscatter-plot

Matplotlib colorbar log2


I would like to know how to make the ticks on a colorbar show for log2.

import matplotlib.pyplot as plt
from matplotlib import ticker
x = np.arange(1000)
y = x.copy()
c = x.copy()
scatter_plot = plt.scatter(x, y, c=c, cmap='viridis', norm=matplotlib.colors.LogNorm())
formatter = ticker.LogFormatter(2)
cbar = plt.colorbar(scatter_plot, format=formatter)
plt.show()

This gives me this image:
Colorbar image

As you can see there are some additional ticks, but it doesn't apply them properly. I want the ticks to be displayed as log2. Any help is appreciated.


Solution

  • you need to use SymLogNorm and pass the parameter base=2 note you need to define a linear range where the plot is linear (to avoid having the plot go to infinity around zero), more info here.

    scatter_plot = plt.scatter(x, y, c=c, cmap='viridis', 
                               norm=matplotlib.colors.SymLogNorm(linthresh=0.001,
                                                                 base=2)
                              )
    
    cbar = plt.colorbar(scatter_plot)
    plt.show()
    

    enter image description here

    Finally, note that, since you have already normalize the data to match to the proper colors using norm parameter using cbar = plt.colorbar() is enought to recover the correct colorbar, passing a without passing a formater to the colorbar.