[metapost] Plotting step functions

Dan Luecking luecking at uark.edu
Wed Dec 7 22:43:08 CET 2011

At 01:20 PM 12/7/2011, you wrote:
>Dear MetaPost folks,
>is there an easy way to define a path and let the lines in between
>connected like a step function?

% Going horizontal, then vertical:
tertiarydef A =| B =
   A--(xpart point 0 of B,ypart(point infinity of A))--B
% Going vertical, then horizontal:
tertiarydef A |= B =
   A--(xpart point infinity of A, ypart point 0 of B)--B

show (0,0) =| (1,1) |= (0,2);

   (0,0)..controls (0.33333,0) and (0.66667,0)
   ..(1,0)..controls (1,0.33333) and (1,0.66667)
   ..(1,1)..controls (1,1.33333) and (1,1.66667)
   ..(1,2)..controls (0.66667,2) and (0.33333,2)
i.e., (0,0)--(1,0)--(1,1)--(1,2)--(0,2)

Caveat: not thoroughly tested.
Note: you can't use
   tertiarydef A -xy- B = etc.
Because Metapost interprets A and xy as the arguments and -
as the operator, then complains of a missing =. However, you
can use
   tertiarydef A xy B = etc.
It is a matter of how MP parses symbolic tokens. A symbolic
token can be a sequence of letters and underscores, but letters
and -'s don't get parsed as one token.

A different approach is to view the path as just a way to encode
the nodes, and then define drawing operations that loops through
the nodes, drawing the steps that connect them.

% First a couple of abbreviations
% For changing y first:
def yx (expr a, b) = (xpart a, ypart b) enddef;
% For changing x first:
def xy (expr a, b) = (xpart b, ypart a) enddef;

def draw_steppedyx expr p =
   draw point 0 of p for n=1 upto length p:
     --yx(point (n-1) of p, point n of p)--point n of p
% ditto draw_steppedxy

  draw_steppedyx (0,0)..(1in,1in)..(0,2in) withcolor blue;



Daniel H. Luecking
Department of Mathematical Sciences
Fayetteville, Arkansas

More information about the metapost mailing list