SVG Cartesian Viewport

When dealing with the presentation of graphs, a cartesian coordinate system (y-axis up) is more advantageous than SVG's (y-axis down). I show you a simple way to establish a cartesian viewport inside your SVG document, based on group transforms.

cartesian viewport

Let

To achieve the desired transform (from cartesian to SVG coords), we need to consider the single steps:
  1. move the upper left corner of the viewport into the origin (cartesian coords).
  2. reflect at the x-axis to get y-axis down.
  3. scale from our cartesian coords to SVG coords.
  4. move viewport to upper left corner (x0,y0) (SVG coords).
This reads in matrix notation (read from right to left)

   [ 1 0 x0]   [ sx 0  0]   [ 1  0 0 ]   [ 1  0 -xmin ]   [ sx  0  -sx*xmin + x0 ]
   [ 0 1 y0] * [ 0  sy 0] * [ 0 -1 0 ] * [ 0  1 -ymax ] = [ 0  -sy  sy*ymax + y0 ]
   [ 0 0 1 ]   [ 0  0  1]   [ 0  0 1 ]   [ 0  0  1    ]   [ 0   0         1     ]

   with

   sx = w/(xmax-xmin)
   sy = h/(ymax-ymin)
We implement this via an ECMAScript function
   function CartesianViewport(group, x0, y0, width, height, xmin, xmax, ymin, ymax)
   {
      if (group)
         group.setAttribute("transform", "matrix(" +  width/(xmax-xmin)               + "," +
                                                      0                               + "," +
                                                      0                               + "," +
                                                     (-height/(ymax-ymin))            + "," +
                                                     (-width/(xmax-xmin) * xmin + x0) + "," +
                                                     (height/(ymax-ymin) * ymax + y0) + ")"  );
   }

Take care of the side effect when using text in this cartesian viewport, that it is (unequally) scaled and reflected.

Here is the example

Now we understand transformations one more bit better.


© 2000 MecXpert