Plotting a step (piecewise) function with vertical lines

alex314159 picture alex314159 · Nov 14, 2011 · Viewed 7.1k times · Source

Trying to plot a signal function of 0 and 1, much like the solution given to the question below: How to plot non-numeric data in Matplotlib

However, I'd like to have vertical lines instead of bent ones when the function goes from 0 to 1. So for instance if f(x)=0 for x = 1 2 3 4 and f(x) = 1 thereafter, I'd like a horizontal line at y=0 up to x=5, and a vertical line at x=5 going from y=0 to y=1, and then a horizontal line at y=1 thereafter

Can this be done within the plot function? Or do I need to draw a ton of squares?

Thanks!

Answer

petrichor picture petrichor · Nov 14, 2011

You can use stairs or area functions. As shown here:

%# Sample input
x = 1:10;
y = [0 0 0 0 1 1 1 1 1 1];

subplot(2,1,1)
stairs(x,y)
title('Stairs chart (non area)')

subplot(2,1,2)
x = [x;x];
y = [y;y];
area(x([2:end end]),y(1:end))
title('Stairs area')

Stairs with area