MATLAB: Multiple X axis in different scale, but one y axis

axisgraphhydrostaticslineMATLABMATLAB C/C++ Graphics Librarymultiple axesmultiple x axesplotx axisx tick labels

Hello,
How to Add Multiple X axis in different scale? Please help me? It will look like this:

Best Answer

Matlab does not support mutliple x axes other than the axes at the upper and lower borders of the plot.
One way to include multiple axis units is to create multi-lined x-axis ticks. The upper axis will be your main axis used to plot your data. Then define the axis limits for all additional pseudo-axes and compute the tick values for each pseudo-axis so they align with the x-ticks on the main axis. Use those value to create the multi-lined x-tick labels.
Follow the demo below and adjust it to fit your needs.
Demo
% Set up main axis (on top)
clf()
ax = axes();
ax.XTick = 0:200:2800;
ax.XLim = [0,2800];
% Set axis limits for all other axes
additionalAxisLimits = [...
0, 1400; % axis 2
19.2, 23.4; % axis 3
0.2, 3]; % axis 4
% Compute tick values for each axis to align with main axis
additionalAxisTicks = arrayfun(@(i){linspace(additionalAxisLimits(i,1), ...
additionalAxisLimits(i,2),numel(ax.XTick))}, 1:size(additionalAxisLimits,1));
% Set up multi-line ticks
allTicks = [ax.XTick; cell2mat(additionalAxisTicks')];
tickLabels = compose('%4d\\newline%4d\\newline%.1f\\newline%.1f', allTicks(:).');
% The %4d adds space to the left so the labels are centered.
% You'll need to add "%.1f\\newline" for each row of labels (change formatting as needed).
% Alternatively, you can use the flexible line below that works with any number
% of rows but uses the same formatting for all rows.
% tickLabels = compose(repmat('%.2f\\newline',1,size(allTicks,1)), allTicks(:).');
% Decrease axis height & width to make room for labels
ax.Position(3:4) = ax.Position(3:4) * .75; % Reduced to 75%
ax.Position(2) = ax.Position(2) + .2; % move up
% Add x tick labels
set(ax, 'XTickLabel', tickLabels, 'TickDir', 'out')
% Define each row of labels
ax2 = axes('Position',[sum(ax.Position([1,3]))*1.08, ax.Position(2), .02, 0.001]);
linkprop([ax,ax2],{'TickDir','FontSize'})
axisLabels = {'Distance (t)','Area (m^2)','Cnt from 0 (m)','KB (m)'}; % one for each x-axis
set(ax2,'XTick',0.5,'XLim',[0,1],'XTickLabel', strjoin(axisLabels,'\\newline'))
ax2.TickLength(1) = 0.2; % adjust as needed to align ticks between the two axes
Similar examples in the forum