Search code examples
matlabplotmatlab-figuresubplot

Same x-axis for two different subplots in MATLAB


I want have a line and bar plot in a figure in MATLAB. How can I have same x-axis for both graphs? The below bar plot x-axis should be same as above x-axis. I want retain the ability of comparing figures.

Figure link: Click Here


Solution

  • You can use linkaxes function:

    figure
    ax1 = subplot(2,2,1);
    x1 = linspace(0,6);
    y1 = sin(x1);
    plot(x1,y1)
    
    ax2 = subplot(2,2,2);
    x2 = linspace(0,10);
    y2 = sin(2*x2);
    plot(x2,y2)
    
    ax3 = subplot(2,2,[3,4]);
    x3 = linspace(0,16);
    y3 = sin(6*x3);
    plot(x3,y3)
    
    linkaxes([ax1,ax2,ax3],'x')
    

    usage:

    linkaxes(ax) links the x- and y-axis limits of the Axes objects specified in the vector ax. The linkaxes function chooses limits that incorporate the current limits for all the linked axes.

    linkaxes(ax, option) links the axes ax according to the specified option. The option argument can be one of these values:

    'x' Link x-axis only.
    'y' Link y-axis only.
    'xy' Link x-axis and y-axis.
    'off' Remove linking.

    Reference here: https://www.mathworks.com/help/matlab/ref/linkaxes.html

    If you have a matlab older than 2006 you can follow this: https://www.mathworks.com/matlabcentral/fileexchange/7169-samexaxis-nice-subplots-with-same-x-axis