Error in MATLAB colorbar tick labeling?

こ雲淡風輕ζ 提交于 2019-12-06 07:22:51

Why is this happening?
Manually changing the TickLabels changes the TickLabelsMode property to manual and the control gets lost for zooming/panning/resizing the figure window.


How can this be fixed?

  • Use a listener that will adjust the ticks itself. It may require undocumented features. You can take ideas on implementing a listener for colorbar from Yair Altman's this utility. This is for ticklabels of axes and would require some tweaking to work for colorbar.

or a relatively simpler approach would be to:

  • Change the 'TicksMode' to manual i.e.:
    Before this line h.TickLabels{end} = ['>' h.TickLabels{end}];, include this line:

    set(h, 'Ticks', get(h,'Ticks'));  %or h.Ticks = h.Ticks; for >= R2014b
    

    This ensures that the ticks remain the same and hence the number of ticks also remains the same and therefore ticklabels will not malfunction on zooming/panning/resizing the figure window.

    If you want to have more or less ticks than you originally get then set them as:

    %Adjust the increment as desired. I set it as 1 (default)
    set(h, 'Ticks', in1:1:in2);       %or h.Ticks = in1:1:in2; for >= R2014b
    %where in1 and in2 are the 1st and 2nd input args you used for caxis respectively
    

or if you're only concerned with the output jpeg file and your ticklabels are malfunctioned in the output image file then:

  • Set the PaperUnits / PaperPosition at the beginning of the plotting instead of doing that at the end. This will not automate the ticklabels but will only make the temporary adjustment.

As Sardar wrote, the only option to solve this automatically, and not lose the auto-scaling of the ticks when the figure window size is changed is to add a listener. This is how to do it:

Copy the following function to an m-file, and save it in the folder you work on this figure (i.e. your current path):

function set_cb_lables
% add '>' to the last tick label in all colorbars

h = findobj(gcf,'Type','Colorbar'); % get all colorbars handels
set(h,{'TickLabelsMode'},{'auto'}); % change thier mode to 'auto'
tiklbl = get(h,{'TickLabels'}); % get all tick labels after the change
for k = 1:numel(tiklbl) 
    tiklbl{k}{end} = ['>' tiklbl{k}{end}]; % add '>' to the last tick
end
set(h,{'TickLabels'},tiklbl); % replace the current ticklabels with tiklbl
end

Then, in your code, add this line after the loop:

set(gcf,'SizeChangedFcn','set_cb_lables'); % aplly the function 'set_cb_lables' upon any size change

This will add '>' automatically to the last tick label upon any resizing of the figure.

This solution is better than just getting the ticks before adding the '>' because now if the window gets bigger, the colorbar is populated automatically with more ticks.

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