Search code examples
matlabmatlab-figure

How to make multiple graphs with varying x-axis?


I need to plot multiple graphs in the same y-axis, but the x-axis is a bit tricky for me:

Assuming it goes from 0 to a, increasing by one, it needs to have an overall of a-1 different intervals.

Each one of them should finish at a, but it also has to have a different initialisation point. Only the first starts at 0, while each next one, starts by the previous plus one, as in the shape below. The two dashed lines, I used to visualise my thoughts as clear as I could, are not necessary.

I would appreciate any help!

enter image description here


Solution

  • Replicate your original interval 0 ... a a times (from my understanding, you'll have a intervals, not a-1), such that you get a matrix X of size [a x a+1]. Set the lower left triangle of X to NaN, so that the rows now represent your (shortening) intervals. Do your calculations on X. Pay attention, these have to support/neglect NaN values properly.

    After that, you need to adjust the values in X properly, so that the intervals are plotted subsequently. Basically, we add some fixed value to each row.

    Last, we need the proper xticks and xticklabels. Therefore, we extract all values from X and the modified X and get rid of the NaN values.

    Here's a complete code snippet:

    % Parameter
    a = 7;
    
    % Initialize intervals
    X = repmat(0:a, a, 1);
    X = X .* (ones(size(X)) + tril(nan(size(X)), -1));
    
    % Calculation on these intervals; attention: there are NaN in X
    Y = sin(X / a * 2 * pi);
    
    % Modify X for plotting
    X_plot = X;
    X_plot(2:end, :) = X_plot(2:end, :) + cumsum(a:-1:2).';
    
    % Get xticks
    xt = X_plot.';
    xt = xt(:);
    xt(isnan(xt)) = [];
    
    % Get xticklabels
    xtl = X.';
    xtl = xtl(:);
    xtl(isnan(xtl)) = [];
    
    % Plot
    plot(X_plot.', Y.');
    xticks(xt);
    xticklabels(xtl);
    

    The output (Octave 5.1.0, also tested with MATLAB Online) looks like this:

    Output

    If you only want for example the start and end of each interval, you must further pre-process xt and xtl.

    Hope that helps!