Search code examples
matlabplotgradientaxiscolorbar

Making colorbar tick labels a string above and below bar, remove ticks - Matlab


I am trying to reproduce the colorbar below for my chart. Specifically it is the string colorbar axis title (above and below the colorbar) that I am struggling with, the rest seems fine.

desired colorbar Below is my current code:

    time_begin  = [1981, 1, 1, 0,0,0];
    time_end    = [2010,12,31,23,0,0];
    years       = (time_begin(1):time_end(1))';
    nyears      = length(years);
    TXx1 = randi(100, 288, 192, 30);
    lat = rand(192, 1);
    lon = rand(288, 1);
    time = rand(30,1);
    M = numel(lon);
    N = numel(lat);
    slope1 = zeros(M, N);
    intercept1 = zeros(M, N);
    T = numel(time);
    x = ([ones(T, 1) years]);
    for i = 1 : M
        for j = 1 : N
            y1 = squeeze(TXx1(i, j, :));
            c = regress(y1, x);
            intercept1(i, j) = c(1);
            slope1(i, j) = c(2);      
        end
    end
    TXx2 = randi(100, 288, 192, 30);
    slope2 = zeros(M, N);
    intercept2 = zeros(M, N);
    T = numel(time);
    x = ([ones(T, 1) years]);
    for i = 1 : M
        for j = 1 : N
            y2 = squeeze(TXx2(i, j, :));
            c = regress(y2, x);
            intercept2(i, j) = c(1);
            slope2(i, j) = c(2);      
        end
    end
    figure()
    set(gcf, 'color', 'w'); 
    temp = [slope1(:) slope2(:)];
    temp(temp == 0) = NaN;
    [Q,Qc] = hist3(temp,'Nbins',[100 100],'CDataMode','auto');
    Qx = cell2mat(Qc(1));
    Qy = cell2mat(Qc(2));
    Q = Q';
    Q = Q./trapz(Qy,trapz(Qx,Q,2));
    surf(Qx,Qy,Q,'FaceColor','interp','EdgeColor','none')
    grid off
    set(gca, 'Fontsize', 12, 'Fontweight', 'Bold'); %added
    cmap = jet(500);
    cmap(1,:) = [1,1,1];
    colormap(cmap);
    h=colorbar;
    set(h,'position',[.91 .34 .031 .475]) %[xposition yposition width height].
    set(get(h,'ylabel'),'string','Point density'); 
    set(h,'XTickLabel',{'Low',' ',' ',' ',' ','High',}); 
    view(0,90)

Here is my current colourbar: current colorbar


Solution

  • Replace this line:

    set(h,'XTickLabel',{'Low',' ',' ',' ',' ','High',}); 
    

    with:

    h.YTick = h.Limits;
    h.YTickLabel = {'Low', 'High'};
    

    This makes two tick-lines and two tick labels. By setting YTicks of the colorbar to its limits, the tick-lines get overlapped by colorbar boundary. So these get hidden and now there is no need to remove them.
    However there is this TickLength property which can be used otherwise i.e.

    h.TickLength = 0;
    

    Result:

    result