Search code examples
matlabmatlab-figure

How to repeat same values in x axis of matlab figures?


I have two functions which their 'x' are between 1 & 30 (1<=x<=30) and each of them has its own 'y'. I want to plot them in a same diagram and draw a vertical line between them (separate them):

1<=x<=30 for function 1
x=31 separator
32<=x<=61 for function 2

This is the code:

y1=[6.5107   28.1239   15.0160   24.9586   17.6224   12.7936   21.9143    7.7560   27.4761    3.1279    8.3063   17.4207 8.3265    0.7540   13.2846   22.8183   25.7289   13.5553   18.0556   19.1853   20.2442    9.0290    5.3196    2.5757 21.6273    8.9054    2.0535    5.0569   22.7735   14.7483];
y2=[13.5876    5.7935    6.4742         0    7.7878         0    8.6912    0.4459   11.9369   10.4926    9.2844   10.4645 4.0736    9.0897    8.4051    0.7690   15.9073    3.7413    8.5098    9.7112    1.3231    8.5113    8.7681    4.1696 12.9530    0.6313   19.9750    0.0664    9.9677   10.1181];
%function 1
bar(1:30,y1,'r');
hold on
% a vertical line from x=31
plot([31 31],get(gca,'ylim'))
%function 2
bar(32:61,y2,'b');

But when I plot them, the x axis of function 1 (left function) in our diagram is 1:30 and the x axis of function 2 (right function) in our diagram is 32:61. But I want to show the x axis values of both of them as 1:30 and not one as 1:30 and the other as 32:61. (Please see the attachment). How can I do that? enter image description here


Solution

  • I suggest adding two lines of code. You can tweak the starting value and the step size to get the aesthetics you want using set, gca, and xlim.

    set(gca,'XTick',[0 2:2:61],'XTickLabel',[0 2:2:30 2:2:30])
    xlim([0 62])
    

    Example demonstrating repeated x values on x tick labels

    Other approaches may be more efficient but hopefully this lets you keep moving forward.

    As already pointed out in the comments, subplot may work well too.

    Subplot Example

    figure
    s(1) = subplot(1,2,1)
    b1 = bar(1:30,y1,'r');
    s(2) = subplot(1,2,2)
    b2 = bar(1:30,y2,'b');
    title(s(1),'Function 1')
    title(s(2),'Function 2')
    
    % Cosmetics
    xRng = [0 31];
    yRng = [0 max(max(s(1).YLim),max(s(2).YLim))];
    for k = 1:2
    xlim(s(k),xRng)
    s(k).YLim = yRng;   % Ensure both vertical axes are same (for fair comparison)
    s(k).YGrid = 'on';
    end
    

    Tested with MATLAB R2017a