matlabplot

How to set upper x-axis ticks values and locations in MATLAB?


I am trying to set the upper x-axis (ax2) tick values and locations.

x_a = linspace(71.8131,36.9931,10);
y = linspace(0.16,1,10);
x_b = linspace(0.0163,0.0069,10)./0.1016;
figure;
ax1 = axes;
plot(ax1, x_a, y, 'k');
ax2 = axes('Position', ax1.Position, ...
           'XAxisLocation', 'top', ...
           'YAxisLocation', 'right', ...
           'Color', 'none', ...
           'XColor', '#88419d', ...
           'YColor', 'none', ...
           'Box', 'off');
ax2.YLim = ax1.YLim;

new_tick_locations = linspace(30, 80, 6);
new_tick_labels = arrayfun(@(val) sprintf('%.2f', val/500), new_tick_locations, 'UniformOutput', false);

set(ax2, 'XTick', new_tick_locations, 'XTickLabel', new_tick_labels);
% linkaxes([ax1 ax2], 'xy');

hold(ax2, 'on');
plot(ax2, x_b, y, 'r');

This code doesn't show the ax2 ticks at all. I need them to show and to be aligned with the lower x axis labels [30, 40, 50, 60, 70, 80]. How can I fix this? Thank you in advance.


Solution

  • I think the problem is that you're dividing new_tick_locations by 500 for the labels, but you need to do this for the values too. I would do this:

    new_tick_locations = linspace(30, 80, 6)/500;
    new_tick_labels = arrayfun(@(val) sprintf('%.2f', val), new_tick_locations, 'UniformOutput', false);
    
    set(ax2, 'XTick', new_tick_locations, 'XTickLabel', new_tick_labels);
    line(ax2, x_b, y, Color='r');