MATLAB设置两行xticklabels以及colorbar宽度

博客介绍了如何在MATLAB中处理长X轴标签问题,通过自定义text实现时间轴的时分和月日分两行标注,并详细展示了调整过程。同时,文章还涉及到了colorbar的宽度调整,以及在调整后处理gca和colorbar重叠的问题,提供了一整套代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近画的一幅图的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值