Search code examples
matlabplotpositionmatlab-figurecolorbar

Obtain full size of colorbar in Matlab


I am writing a plot automation routine for Matlab. However, I am having issues to assess the (horizontal) size of colorbars. I can use the following to get the size of the colorbar:

cb = findall(groot,'Type','colorbar'); % get colorbar
xwidth = cb.Position(3);

This will give me the horizontal size of the colorbar, but EXCLUDES labels and tick labels.

Do you have an idea how to obtain the full size of both the bar and the labels?

Thanks in advance


Solution

  • In versions of MATLAB prior to R2014b, a colorbar was simply an axes object in disguise so you could easily use the OuterPosition property of the colorbar to get the position of the colorbar (including labels and tick labels). However, in R2014b, the colorbar is it's own graphics object and the underlying axes is no longer accessible.

    One possible workaround is to create an invisible axes object on top of the colorbar (that has the same tick marks and labels) and get the OuterPosition of that.

    function pos = getColorbarPosition(cb)
    
        tmp = axes('Position', cb.Position, 'YAxisLocation', 'right', ...
                'YLim', cb.Limits, 'FontSize', cb.FontSize, 'Units', cb.Units, ...
                'FontWeight', cb.FontWeight, 'Visible', 'off', ...
                'FontName', cb.FontName, 'YTick', cb.Ticks, ...
                'YTickLabels', cb.TickLabels, 'XTick', []);
    
        if ~isempty(cb.Label)
            ylabel(tmp, cb.Label.String, 'FontSize', cb.Label.FontSize, ...
            'FontWeight', cb.Label.FontWeight, 'FontWeight', cb.Label.FontWeight)
        end
    
        pos = get(tmp, 'OuterPosition');
    
        delete(tmp);
    end