How can one get the data vectors from the output of the stairs function in Matlab? I tried the following
h = stairs(x,y);
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!
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:
x
and y
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') ;