Search code examples
matlabmatlab-figure

Get data vector from stairstep plot Matlab


How can one get the data vectors from the output of the stairs function in Matlab? I tried the following

h = stairs(x,y);

enter image description here

Then I get the data from the handle:

x = h.XData; 
y = h.YData; 

but when x and y are plotted, they look as a piece-wise function, not the stairs.

Any help is appreciated. Thanks!

enter image description here


Solution

  • The data necessary to display a stairs plot are relatively easy to generate by yourself.

    Assuming you have x and y. To generate 2 vectors xs and ys such as plot(xs,ys) will display the same thing than stairs(x,y), you can use the following 2 steps method:

    • replicate each element of x and y
    • offset the new vectors by one element (remove the first point of one vector and the last point of the other)

    Example with code:

    %% demo data
    x = (0:20).';
    y = [(0:10),(9:-1:0)].' ;
    
    hs = stairs(x,y) ;
    hold on
    
    %% generate `xs` and `ys`
    % replicate each element of `x` and `y` vector
    xs = reshape([x(:) x(:)].',[],1) ;
    ys = reshape([y(:) y(:)].',[],1) ;
    
    % offset the 2 vectors by one element
    %  => remove first `xs` and last `ys`
    xs(1)   = [] ;
    ys(end) = [] ;
    
    % you're good to go, this will plot the same thing than stairs(x,y)
    hp = plot(xs,ys) ;
    
    % and they will also work with the `fill` function
    hf = fill(xs,ys,'g') ;
    

    enter image description here