Search code examples
matlabmatlab-figuresurfacecolorbar

How can I display a log scale colorbar with Matlab R2015a?


I am trying to display a 3D plot with the function surf in Matlab and I need it to be in log scale for the z-axis. So here is what I am doing :

surf(X,Y,Z)
set(gca,'zscale','log')

But I would like the colorbar to appear in log scale, with labels like 10^(-6), 10^(-5), 10^(-4),...

Looking it up, I found out about the solution

h = colorbar
set(h,'YScale','log')

but it's not working with the newest versions of Matlab because the 'YScale' parameter doesn't exist anymore.

Any idea?

Thanks a lot.


Solution

  • Even if you can change the colorbar axis and labels to a log scale, your data is still not in log scale, and so the colorbar will appear strange. To fix this I can suggest another dummy axes to hold the colorbar. Here is how:

    Let's say you plot this:

    [X,Y,Z] = peaks(50);
    s = surf(X,Y,Z);
    set(gca,'zscale','log')
    h = colorbar;
    

    Our next step is to get the axes position after the colorbar insertion (for future use):

    axpos = s.Parent.Position;
    

    Now we create new axes, hide them, and add a colorbar in the same position of the first one:

    axes;
    axis off
    cb = colorbar('Position',h.Position);
    

    Next we adjust the colobar axis to values that are displayed in the plot (since Z<=0 are not displayed):

    caxis(log10([min(Z(Z>0)) max(Z(:))]))
    

    we change the colorbar ticks labels to the log-scale format:

    cb.TickLabels = sprintf('10^{%1.1f}\n',cb.Ticks);
    

    Finally, we delete the first colorbar, and set the axes position back to axpos:

    delete(h)
    set(s.Parent,'Position',axpos)
    

    and we get:

    enter image description here