我正在绘制9个子图,如下图所示,其中一个颜色条用于三个子图。
在这里,我想将颜色条中的最高值显示为> value
,令人惊讶的是,当我手动编辑刻度标签为h.TickLabels{end} = ['>' h.TickLabels{end}];
时,颜色条开始重复该值。
当我删除h.TickLabels{end} = ['>' h.TickLabels{end}];
时,颜色条显示没问题。当我更改set(gcf, 'PaperUnits', 'inches', 'PaperPosition', [0 0 8 8])
中的图形大小时,[0 0 5 5]
colorbar标签再次发生变化。
如何解决此错误?
以下是我的工作示例和输出图像:
data = [1 2 3; 5 7 3; 12 29 14; 1 7 3; 2 8 3; 5 4 1; 2 2 1; 2 3 1; 1 5 2];
for i=1:9
subplot(3, 3, i)
plot(data(i,:));
if ismember(i, [1:3])
caxis([0 20])
if i==3
h = colorbar('Fontsize', 6, 'LineWidth', 0.15, 'TickDirection', 'out',...
'TickLength', 0.02);
set(h, 'Position', [.935 .6867 .01 .2533])
h.TickLabels{end} = ['>' h.TickLabels{end}];
end
end
if ismember(i, [4:6])
caxis([0 6])
if i==6
h = colorbar('Fontsize', 6, 'LineWidth', 0.15, 'TickDirection', 'out',...
'TickLength', 0.02);
set(h, 'Position', [.935 .3733 .01 .2533])
h.TickLabels{end} = ['>' h.TickLabels{end}];
end
end
if ismember(i, [7:9])
caxis([0 4])
if i==9
h = colorbar('Fontsize',6, 'LineWidth', 0.15, 'TickDirection', 'out',...
'TickLength', 0.02);
set(h, 'Position', [.936 .06 .01 .2533])
h.TickLabels{end} = ['>' h.TickLabels{end}];
end
end
end
set(gcf, 'PaperUnits', 'inches', 'PaperPosition', [0 0 8 8])
print('test', '-djpeg', '-r300')
close all
为什么会这样?
手动更改TickLabels
会将TickLabelsMode
属性更改为手动,并且控件会因缩放/平移/调整图形窗口而丢失。
怎么解决这个问题?
colorbar
那里获得关于为this utility实现一个监听器的想法。这是针对轴的刻度标签,需要一些调整才能适用于colorbar
。或者相对简单的方法是:
'TicksMode'
更改为手动即:
在此行之前h.TickLabels{end} = ['>' h.TickLabels{end}];
,包括这一行:
set(h, 'Ticks', get(h,'Ticks')); %or h.Ticks = h.Ticks; for >= R2014b
这确保了刻度线保持不变,因此刻度线的数量也保持不变,因此刻度标签在缩放/平移/调整图形窗口大小时不会出现故障。
如果您想要比您最初获得的更多或更少的刻度,请将它们设置为:
%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
或者如果您只关注输出jpeg文件并且输出图像文件中的ticklabels出现故障,则:
PaperUnits
/ PaperPosition
,而不是在结束时执行此操作。这不会自动化ticklabels,但只会进行临时调整。作为Sardar wrote,自动解决此问题的唯一选择,并且在更改图形窗口大小时不会丢失刻度线的自动缩放是添加侦听器。这是怎么做的:
将以下函数复制到m文件,并将其保存在您在此图上工作的文件夹中(即当前路径):
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
然后,在您的代码中,在循环之后添加以下行:
set(gcf,'SizeChangedFcn','set_cb_lables'); % aplly the function 'set_cb_lables' upon any size change
这将在任何尺寸调整大小时自动将“>”添加到最后一个刻度标签。
这个解决方案比在添加'>'之前获得滴答更好,因为现在如果窗口变大,颜色条将自动填充更多刻度。