2

I have a function that create the cumulative probability that a certain time is kept (value between 0 and 1 on the Y-axis, and amount of days on the x-axis). Since I know the distance, I thought about adding a secondary x-axis with the average speed that the time correlates to.

Adding a secondary axis was relative easy like this example, as start I manage to set the xlim correct and also to reverse it.

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

There are two problems, first the rounding have too big impact and second, and more important it isn't a linear correlation between xminb and xmaxb, so I have to add the xticks manually? I tried to do it like this:

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

Hence the now the secondary axis became empty and I don't know how to set different spacing between them (the distance between 12-13 to the right should be larger than between 16 and 17 to the left..)

axel_ande
  • 359
  • 1
  • 4
  • 20

2 Answers2

1

I would use the same 'XTick' and 'Xlim' as in the main axes, and change the 'XTickLabel' property. You can assign any string (or number) to each tick mark.

But be explicit about 'XTick' when you define 'XTickLabel', so the labels are associated to specific locations on the axis. Scaling the figure can change the number of automatically generated tick marks, which would cause your selected labels to appear in the wrong locations.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
0

I thought I post the solution, at little bit like Cris Luengo says, hence quite tricky (IMO) to get correct with decreasing values of the speed (with increased time):

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})

Hope that it helps someone else in the future!

Time as one axis and speed as secondary axis

axel_ande
  • 359
  • 1
  • 4
  • 20