Matlab - 设置辅助轴的xticks甚至不与第一轴

时间:2018-04-13 15:09:19

标签: matlab

我有一个函数可以创建保留特定时间的累积概率(Y轴上的值介于0和1之间,x轴上的天数)。因为我知道距离,所以我考虑添加一个辅助x轴,其中包含时间相关的平均速度。

添加辅助轴相对容易,如this example,因为开始我设法正确设置xlim并将其反转。

xlabel('Time (days)')
xlim([27 38])
a1Pos = get(gca,'Position');
b = axes('Position',[a1Pos(1) a1Pos(2)-.06 a1Pos(3) a1Pos(4)], 'YTick',[],'YTickLabel',[]);
xmaxb = round(dist/(xmaxa*24));
xminb = round(dist/(xmina*24));
set(b,'Units','normalized');
set(b,'Color','none');
set(b, 'XDir','reverse')
set(b,'xlim',[xminb xmaxb])
xlabel(b,'Average speed on the journey (knots)')

First attempt, two axis

有两个问题,首先是舍入有太大的影响而第二个,更重要的是它不是xminb和xmaxb之间的线性相关,所以我必须手动添加xticks?我试着这样做:

set(b,'XTick',[12 13 14 15 16 17])

因此现在辅助轴变空了,我不知道如何在它们之间设置不同的间距(右边12-13之间的距离应该大于左边16到17之间的距离..)

2 个答案:

答案 0 :(得分:1)

我会在主轴上使用相同的'XTick'和'Xlim',并更改'XTickLabel' property。您可以为每个刻度线分配任何字符串(或数字)。

但是在定义'XTickLabel'时要明确'XTick',因此标签与轴上的特定位置相关联。缩放图形可能会更改自动生成的刻度线的数量,这会导致所选标签出现在错误的位置。

答案 1 :(得分:0)

我以为我发布的解决方案,有点像Cris Luengo说的,因此非常棘手(IMO)以降低速度值(增加时间)来纠正:

xmaxb = floor(dist/(xmaxa*24)); %xmaxa = max value of the first xlabel
xminb = ceil(dist/(xmina*24)); %xmina = min value of the first xlabel
bticks_lab = fliplr(xmaxb: 0.5:xminb); % spacing 0.5 for the second axis and flip it.
bticks_loc = (dist./(bticks_lab * 24) - xmina) / (xmaxa-xmina); 
% The new "b" axis got locations between 0 and 1, this took awhile to figure out!
b = axes('Position',[a1Pos(1) a1Pos(2)-.06 a1Pos(3) a1Pos(4)], 'YTick',[],'YTickLabel',[]);
set(b,'Units','normalized');
set(b,'Color','none');
set(b,'XTick',bticks_loc)
set(b,'XTickLabel',{bticks_lab})

希望将来帮助其他人!

Time as one axis and speed as secondary axis