Generating SVG with Mathematica

An example of the use of SymbolicXML

Tom Wickham-Jones Wolfram Research Inc.
27-Jan-2003

What is SVG?

SVG is an XML language for describing two-dimensional graphics. Since it is based on XML any XML aware application can work with SVG. Mathematica has some good tools for working with XML and some specific functions that support SVG, thus it is a good environment for some interesting SVG applications. SVG contains some interesting features including a variety of dynamic features such as animations.

SVG can be rendered with a browser plug-in from Adobe,  http://www.adobe.com/svg. which provides strong support including the animation functions. More information about SVG can be found at the W3C site: http://www.w3.org/Graphics/SVG/.

Mathematica Commands for Generating SVG

Mathematica has a rich graphics language for representing graphics as Mathematica expressions.

p = Graphics[Line[ {{0, 0}, {1, 1}}]]

These print as expressions, if you want to see a graphical expression you use a command such as Show.

Show[p]

Mathematica can write an XML representation of a Mathematica graphics expression into a string with ExportString and into a file with Export.

str = ExportString[p, "SVG"]

A string of XML can be read back into Mathematica with the command ImportString with a format of XML. This returns a symbolic XML expression that is an isomorphic representation of the original XML. The symbolic XML version of the XML can be worked with by standard Mathematica programming techniques. This is demonstrated in the next section.

ImportString[str,  "XML"]

The command XML`SVG`GraphicsToSymbolicSVG goes directly from a Mathematica graphics expression directly to the symbolic XML representation of the SVG.

XML`SVG`GraphicsToSymbolicSVG[p]

Generating an SVG Animation

Mathematica can solve a differential equation:

sol = 
      NDSolve[{ x''[t] + 0.15 x'[t] - x[t] + x[t]^3 == 
            5  Cos[t], 
x[0] == 1, x'[0] == 
            2}, x, {t, 0, 20}]

and then the solution can be plotted.

p = 
        ParametricPlot[
          Evaluate[{x[t], x'[t]} /. sol], {t, 0, 20}];

The graphics object returned by the plot command can be converted to a SymbolXML view of the SVG.

The SVG is larger than the Mathematica graphics language representation,

ByteCount /@ {ExportString[xml,  "XML"], ToString[p, InputForm], 
        ExportString[p, "JPG"]}

Find the XML fragment that holds the line for the solution, it will be the first instance of <polyline points=pts> </polyline>.

Generate a new fragment of symbolic XML that holds an SVG animation, this has the form 
<circle> <animateMotion path=pts/>  </circle>.

Now we add this new fragment back into the original SVG

Export the SymbolicXML out to a file

Export["file.svg", newXML, "XML"]

Open the file in IE with the Adobe plug-in and you'll see a nice animation.