问题
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