MATLAB设置两行xticklabels以及colorbar宽度

最近画的一幅图的X轴是时间,需要标注月份、日期和时分,显然每个xticklabel太长了,于是想要分两行标注,第一行标注时分,第二行标注月日。搜了一圈发现MATLAB并没有实现这个功能的函数,于是只能使用text行数进行实现。实现过程主要是先调整gca的宽度,然后上移为两行text腾出空间。然后设置gca本身的xticklabels为空。根据xticks的位置和y轴的范围设置两行text的范围,最后下移xlabel的范围。

画完之后又发现colorbar太宽了,看起来不美观。结果调整colorbar position之后,gca竟然自动调整了宽度,导致gca和colorbar重叠了,于是又设置了一遍gca的position。下面是示例代码,总体顺序是

(1)画图

(2)画colorbar

(3)调整gca position

(4)标注两行text

(5)调整xlabel的position

(6)调整colorbar的position

(7)重置gca position

clc;clear;
figure;
pcolor(0:10,1:20,rand(20,11));shading interp;
c=colorbar;colormap(cool);
%plot colorbar first and get gca position
ax=gca;
xticks(0:2:10);
xlim([0 10]);

%% add two lines of xitck labels
xticklabels('');
% narrow gca and move up to make space for two lines of xitck labels
ax.Position=[ax.Position(1),ax.Position(2)+ax.Position(4)*0.3,ax.Position(3),ax.Position(4)*0.7];
xTicks = get(gca, 'xtick');
XtickLabelStrs{
    
    1}={
    
    ' 00:00';' 12:00';' 00:00';' 12:00';' 00:00';' 12:00'};
XtickLabelStrs{
    
    2}={
    
    'Jan 24';'Jan 24';'Jan 25';'Jan 25';'Jan 26';'Jan 26'};
xl=xlim; minX=xl(1);maxX=xl(2);
yl=ylim; minY=yl(1);maxY=yl(2);
% You will have to adjust the offset based on the size of figure
VerticalOffset = (maxY-minY)*0.2;
for xx = 1:length(xTicks)
    % Create a text box at every Tick label position
    text(xTicks(xx), minY-VerticalOffset, ...
        [XtickLabelStrs{
    
    1}(xx);XtickLabelStrs{
    
    2}(xx)],...
        'fontsize',9,...
        'HorizontalAlignment','center');
    % 'HorizontalAlignment','center' specifies that the elements of the different lines
    % will be center aligned
end
xlabel('Time [UT]','position',[(minX+maxX)/2,minY-VerticalOffset*2]);
ylabel('Frequency [mHz]');

%% set colorbar width
GcaPosition=ax.Position;
c.Position=[c.Position(1),c.Position(2),c.Position(3)*0.6,c.Position(4)];
% because the gca position will change automaticlly, so you need to reset
% the position of gca as previous;
ax.Position=GcaPosition;

在这里插入图片描述

转载自:https://zhuanlan.zhihu.com/p/138020768

猜你喜欢

转载自blog.csdn.net/wokaowokaowokao12345/article/details/109049884