在 Matlab 中获取全尺寸的 colorbar

Obtain full size of colorbar in Matlab

我正在为 Matlab 编写绘图自动化例程。 但是,我在评估颜色条的(水平)大小时遇到​​问题。 我可以使用以下方法获取颜色栏的大小:

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

这会给我颜色栏的水平尺寸,但不包括标签和刻度标签。

您知道如何获得条形图和标签的完整尺寸吗?

提前致谢

在 R2014b 之前的 MATLAB 版本中,颜色条只是一个伪装的 axes 对象,因此您可以轻松地使用颜色条的 OuterPosition 属性 来获取颜色条(包括标签和刻度标签)。但是,在 R2014b 中,颜色条是它自己的图形对象,底层轴不再可用。

一种可能的解决方法是在颜色栏顶部创建一个不可见的 axes 对象(具有相同的刻度线和标签)并获取 OuterPosition.

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

在matlab2017中colorbar对象有两个重要的大小属性,'Position'和'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)