You could create a second axes on top of the first (at the same location) which has the XAxisLocation
set to 'top'
, has no Color
so it's transparent, has no yticks, and has it's YLim
linked to that of the first axes. Additionally, we can link the Position
values to ensure that if we resize one of the axes, they resize together to maintain their appearance.
figure;
% Create the first axes
hax1 = axes();
% Plot something here
xdata = 1:10;
hplot1 = line(xdata, log(xdata));
% Create a transparent axes on top of the first one with it's xaxis on top
% and no ytick marks (or labels)
hax2 = axes('Position', get(hax1, 'Position'), ... % Copy position
'XAxisLocation', 'top', ... % Put the x axis on top
'YAxisLocation', 'right', ... % Doesn't really matter
'xlim', [2 20], ... % Set XLims to fit our data
'Color', 'none', ... % Make it transparent
'YTick', []); % Don't show markers on y axis
% Plot data with a different x-range here
hplot2 = line(xdata * 2, log(flip(xdata)), 'Color', 'r', 'Parent', hax2);
% Link the y limits and position together
linkprop([hax1, hax2], {'ylim', 'Position'});
% Draw some labels
xlabel(hax1, 'Blue Line')
xlabel(hax2, 'Red Line')
ylabel(hax1, 'Some Value')
% Add a legend? Why not?!
legend([hplot1, hplot2], {'Blue', 'Red'})

Edit by Carl W (the OP)
The code above will cause ugly XTicks when the tick spacings aren't the same top and bottom.
I found a workaround at matlab remove only top and right ticks with leaving box on . I modded the code above slightly to
figure
xdata = 1:10;
plot(xdata)
% get handle to current axes
hax1 = gca;
% set box property to off
set(hax1,'box','off','color','white')
hax2 = axes('Position', get(hax1, 'Position'),'box','off', ... % Copy position
'XAxisLocation', 'top', ... % Put the x axis on top
'YAxisLocation', 'right', ... % Doesn't really matter
'Color', 'none', ... % Make it transparent
'YTick', []);
WARNING: this will not work with plot
, which will override the existing axis assignments.
Since there's no points
function (stupid MathWorks) I had to do line(x,y,'linestyle','none','marker','x','parent',hax2)
to get points.
hplot2 = line(5:25, log((5:25)), 'Color', 'r', 'Parent', hax2);
linkprop([hax1,hax2],{'ylim','Position'});
This gives 