Obtain full size of colorbar in Matlab

回眸只為那壹抹淺笑 提交于 2020-01-11 07:19:09

问题


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


回答1:


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



回答2:


In the matlab2017 the colorbar objects have two important size properties, 'Position' and 'Label.Extent'

cax = colorbar;
cax.Units = 'centimeters'; % I think this sets the units for the child
cax.Label.String = 'A title'; 
% The position of the bar itself as [ left bottom width height ]
cpos = cax1.Position; 
% The position of the label as [ left bottom width height ]
lpos = cax.Label.Extent;
% The width of the colorbar and label is:
totalwidth = cpos(3) + lpos(3)


来源:https://stackoverflow.com/questions/42692628/obtain-full-size-of-colorbar-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!