Search code examples
matlabmatlab-figurecolorbar

Placing tick labels in the centre


I have written a script for a specific colormap, given below:

white=[1 1 1];
yellow=[1 1 0];
orange=[1 0.5 0];
red=[1 0 0];
black=[0 0 0];
custom_map = [white; yellow; orange; red; black]; 
colorbar('YTickLabel',{'None','Moderate','Strong','Severe','Extreme'})
caxis([1,5]);

I would like the tick labels to be placed in the centre of the colorbar, i.e. the label 'white' would be placed in the middle of the white section of the colorbar. Thus far I am having difficulty achieving this.

Is there an easy way to do this?


Solution

  • There already was a hint from Luis in a comment below the answer to your earlier question. Since proper styling the colorbar is a bit tricky, here's a complete example:

    % Custom colormap
    white = [1 1 1];
    yellow = [1 1 0];
    orange = [1 0.5 0];
    red = [1 0 0];
    black = [0 0 0];
    custom_map = [white; yellow; orange; red; black]; 
    n_colors = size(custom_map, 1);
    
    % Generate and show sample data; apply custom colormap
    a = rand(20, 20);
    imagesc(a);
    colormap(custom_map);
    
    % Add styled colorbar
    vmin = 0;
    vmax = 1;
    v_range = vmax - vmin;
    ticks = v_range*(vmin+1/(2*n_colors)):v_range*(1/n_colors):vmax;
    ticklabels = {'white', 'yellow', 'orange', 'red', 'black'};
    colorbar('Ticks', ticks, 'TickLabels', ticklabels);
    % Also works, and Octave compatible:
    % colorbar('ytick', ticks, 'yticklabel', ticklabels);
    caxis([vmin, vmax]);
    

    For proper aligned ticks, you must incorporate the minimum and maximum values of your desired value range (vmin and vmax in the example), as well as the range itself (v_range), and the number of colors (n_colors).

    Here's some output (Octave 5.1.0, but also tested in MATLAB Online):

    Output

    The implementation should be quite flexible. Here's the same data, but for a different vmax = 3:

    Addon #1

    Or, here's the same data with two additional colors:

    Addon #2

    Hope that helps!