XML technologies / XSLT / XSLT Cookbook / Converting XML to SVG / Prebuilt SVG transformation

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

Display data graphically by filling an existing SVG image with values.

Solution

XSLT 1.0

Suppose you need a bar chart. You could create a transformation generating its SVG from scratch, as in Creating reusable SVG chart utilities. For those unfamiliar with graphics, this is challenging. Sometimes the data has a fixed point count. Then create the SVG graphic in a drawing program as a reusable template populated with actual data by XSLT, greatly simplifying the task.

Consider this bar-chart template:

<svg width="650" height="500">
  <g id="axis" transform="translate(0 500) scale(1 −1)">
    <line id="axis-y" x1="30" y1="20" x2="30" y2="450" style="fill:none;stroke:rgb(0,0,0);stroke-width:2"/>
    <line id="axis-x" x1="30" y1="20" x2="460" y2="20" style="fill:none;stroke:rgb(0,0,0);stroke-width:2"/>
  </g>
  <g id="bars" transform="translate(30 479) scale(1 −430)">
    <rect x="30" y="0" width="50" height="0.25" style="fill:rgb(255,0,0);stroke:rgb(0,0,0);stroke-width:0"/>
    <rect x="100" y="0" width="50" height="0.5" style="fill:rgb(0,255,0);stroke:rgb(0,0,0);stroke-width:0"/>
    <rect x="170" y="0" width="50" height="0.75" style="fill:rgb(255,255,0);stroke:rgb(0,0,0);stroke-width:0"/>
    <rect x="240" y="0" width="50" height="0.9" style="fill:rgb(0,255,255);stroke:rgb(0,0,0);stroke-width:0"/>
    <rect x="310" y="0" width="50" height="1" style="fill:rgb(0,0,255);stroke:rgb(0,0,0);stroke-width:0"/>
  </g>
  <g id="scale" transform="translate(29 60)">
    <text id="scale1" x="0px" y="320px" style="text-anchor:end;fill:rgb(0,0,0);font-size:10;font-family:Arial">0.25</text>
    <text id="scale2" x="0px" y="215px" style="text-anchor:end;fill:rgb(0,0,0);font-size:10;font-family:Arial">0.50</text>
    <text id="scale3" x="0px" y="107.5px" style="text-anchor:end;fill:rgb(0,0,0);font-size:10;font-family:Arial">0.75</text>
    <text id="scale4" x="0px" y="0px" style="text-anchor:end;fill:rgb(0,0,0);font-size:10;font-family:Arial">1.00</text>
  </g>
  <g id="key">
    <rect id="key1" x="430" y="80" width="25" height="15" style="fill:rgb(255,0,0);stroke:rgb(0,0,0);stroke-width:1"/>
    <rect id="key2" x="430" y="100" width="25" height="15" style="fill:rgb(0,255,0);stroke:rgb(0,0,0);stroke-width:1"/>
    <rect id="key3" x="430" y="120" width="25" height="15" style="fill:rgb(255,255,0);stroke:rgb(0,0,0);stroke-width:1"/>
    <rect id="key5" x="430" y="140" width="25" height="15" style="fill:rgb(0,255,255);stroke:rgb(0,0,0);stroke-width:1"/>
    <rect id="key4" x="430" y="160" width="25" height="15" style="fill:rgb(0,0,255);stroke:rgb(0,0,0);stroke-width:1"/>
    <text id="key1-text" x="465px" y="92px" style="fill:rgb(0,0,0);font-size:18;font-family:Arial">schlüssel1</text>
    <text id="key2-text" x="465px" y="112px" style="fill:rgb(0,0,0);font-size:18;font-family:Arial">schlüssel2</text>
    <text id="key3-text" x="465px" y="132px" style="fill:rgb(0,0,0);font-size:18;font-family:Arial">schlüssel3</text>
    <text id="key4-text" x="465px" y="152px" style="fill:rgb(0,0,0);font-size:18;font-family:Arial">schlüssel4</text>
    <text id="key5-text" x="465px" y="172px" style="fill:rgb(0,0,0);font-size:18;font-family:Arial">schlüssel5</text>
  </g>
  <g id="title">
    <text x="325px" y="20px" style="text-anchor:middle;fill:rgb(0,0,0);font-size:24;font-family:Arial">Überschrift</text>
  </g>
</svg>

Rendering it produces the following figure.

SVG bar-chart template

Figure: SVG bar-chart template.

The SVG was created with these constraints:

First, five data values require five bars, placed in an SVG group with id="bars". Crucially, transform the bars’ coordinate system so height equals the data value, using transform="translate(30 479) scale(1−430)". The translate moves the bars’ origin to the axes’ origin, while transform flips and scales the Y axis so height height="1" gives a full-height bar. The negative value flips, and 430 scales, 430 being the Y-axis length. Value scale(1,-1) in attribute transform is a placeholder compatible with the dummy data. The stylesheet replaces it when processing real values.

Second, id="key" creates a dummy legend in an SVG group. Its elements match the bars’ order, which the transformation relies on to populate the chart correctly.

Third, four text elements mark the Y-axis scale in a group with id="scale". Each text node has an ID whose numeric suffix gives its quarter-scale position. For example, text 0.50 uses id="scale2" because it is at 2/4 or 1/2. The stylesheet uses this number to map the scale to the real data.

Fourth, add a dummy heading in its own group. Center and anchor it in the graphic so it remains centered when real text replaces it.

Grouping all major chart components simplifies the stylesheet that fills them with real data.

The chart data is sales for your company’s five best-selling products:

<product-sales description="Fünf meistverkauften Produke (in i1000)">
  <product name="Sockenwalter">
    <sales multiple="1000" currency="USD">70</sales>
  </product>
  <product name="Hosenjäger">
    <sales multiple="1000" currency="USD">880</sales>
  </product>
  <product name="Wunderhüte">
    <sales multiple="1000" currency="USD">1000</sales>
  </product>
  <product name="Schürzenträger">
    <sales multiple="1000" currency="USD">532</sales>
  </product>
  <product name="Nasenchlorer">
    <sales multiple="1000" currency="USD">100</sales>
  </product>
</product-sales>

The stylesheet combines prebuilt SVG and this data to plot actual values:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:math="http://www.exslt.org/math" exclude-result-prefixes="math">
  <!-- Kopiere standardmäßig das SVG auf die Ausgabe -->
  <xsl:import href="../util/copy.xslt"/>
  <!-- Wir brauchen max, um den maximalen Datenwert zu finden. Wir benutzen max für die Skalierung. -->
  <xsl:include href="../math/math.max.xslt"/>
  <!-- Der Dateiname wird als Parameter übergeben -->
  <xsl:param name="data-file"/>
  <!-- Wir definieren den Ausgabetyp als SVG-Datei und referenzieren die SVG-DTD. -->
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" doctype-public="-//W3C//DTD SVG 1.0/EN" doctype-system="http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"/>
  <!-- Wir laden alle Datenwerte in eine Knotenmengenvariable, um leichter darauf zugreifen zu können. -->
  <xsl:variable name="bar-values" select="document($data-file)/*/*/sales"/>
  <!-- Wir laden die Datennamen aller Balken in eine Knotenmengenvariable, um leichter darauf zugreifen zu können. -->
  <xsl:variable name="bar-names" select="document($data-file)/*/*/@name"/>
  <!-- Wir finden den maximalen Datenwert -->
  <xsl:variable name="max-data">
    <xsl:call-template name="math:max">
      <xsl:with-param name="nodes" select="$bar-values"/>
    </xsl:call-template>
  </xsl:variable>
  <!-- Aus rein ästhetischen Gründen skalieren wir das Diagramm, damit der maximal darstellbare Wert 10% größer ist als das echte Datenmaximum. -->
  <xsl:variable name="max-bar" select="$max-data + $max-data div 10"/>
  <!-- Da alle Komponenten des Diagramms in einer benannten Gruppe sind, können wir das Stylesheet leicht so strukturieren, dass es alle Gruppen findet und die passende Transformation anwendet. -->
  <!-- Wir kopieren die scale-Gruppe und ersetzen die Textwerte durch Werte, die den Wertebereich unserer Daten spiegeln. Wir nehmen den numerischen Teil einer id, um das richtige Viel-fache von 0.25 zu erzeugen. -->
  <xsl:template match="g[@id='scale']">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:for-each select="text">
        <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:variable name="factor" select="substring-after(@id,'scale') * 0.25"/>
          <xsl:value-of select="$factor * $max-bar"/>
        </xsl:copy>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>
  <!-- Bei allen key-Komponenten ersetzen wir einfach den Textwert -->
  <xsl:template match="g[@id='key']">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates select="rect"/>
      <xsl:for-each select="text">
        <xsl:variable name="pos" select="position( )"/>
        <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:value-of select="$bar-names[$pos]"/>
        </xsl:copy>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>
  <!-- Wir ersetzen die Überschrift durch eine Beschreibung, die aus den Daten extrahiert wird. Diese Überschrift hätten wir auch als Parameter übergeben können. -->
  <xsl:template match="g[@id='title']">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:for-each select="text">
        <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:value-of select="document($data-file)/*/@description"/>
        </xsl:copy>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>
  <!-- Die Balken werden erzeugt, indem 1) das transform-Attribut durch eines ersetzt wird, das abhängig vom Wert $max-bar skaliert, 2) der Datenwert als Höhe des Balkens gesetzt wird. -->
  <xsl:template match="g[@id='bars']">
    <xsl:copy>
      <xsl:copy-of select="@id"/>
      <xsl:attribute name="transform">
        <xsl:value-of select="concat('translate(60 479) scale(1 ', −430 div $max-bar,')')"/>
      </xsl:attribute>
      <xsl:for-each select="rect">
        <xsl:variable name="pos" select="position( )"/>
        <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:attribute name="height">
            <xsl:value-of select="$bar-values[$pos]"/>
          </xsl:attribute>
        </xsl:copy>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Applying it to the SVG template gives this chart:

An XSLT-generated SVG bar chart

Figure: An XSLT-generated SVG bar chart.

XSLT 2.0

Rather than repeat the solution for 2.0, here are only the necessary or desirable changes.

Use the built-in XPath 2.0 function max instead of our version under Numbers and calculations:

<xsl:variable name="bar-values" select="document($data-file)/*/*/sales" as="xs:double*"/>
  <!-- Wir bestimmen den maximalen Datenwert -->
<xsl:variable name="max-data" select="max($bar-values)"/>

But XSLT 2.0 does not allow type tricks. Explicitly convert strings to numbers and back:

<xsl:template match="g[@id='scale']">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:for-each select="text">
      <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:variable name="factor" select="number(substring-after(@id,'scale')) * 0.25"/>
        <xsl:value-of select="$factor * $max-bar"/>
      </xsl:copy>
    </xsl:for-each>
  </xsl:copy>
</xsl:template>

The shorter xsl:attribute form is also possible. Note the required number-to-string conversion:

<xsl:attribute name="transform" select="concat('translate(60 479) scale(1 ', string(-430 div $max-bar),')')"/>

Discussion

Direct SVG generation soon involves much math, trial and error and frustration, especially without graphics expertise. This recipe avoids that by using SVG drawn manually in an editor. SVG’s transformations also simplify mapping data into graphics.

There are obvious limitations.

First, know the data count in advance. A general chart program calculates and distributes bars after examining runtime data. Partly work around this with, say, ten bars, removing unused ones. But mapping two values onto a ten-bar layout leaves aesthetically poor gaps.

Second, even more sophisticated graphics remain limited to linear mappings. It is unclear whether the approach adapts easily to pie charts, where changing a slice’s area requires more than one attribute.

Third, the data source, template and stylesheet are coupled. Each use needs a new template and stylesheet, potentially costing more over time than a general solution from the outset.

Despite these limits, it is a useful starting point for learning SVG. An SVG editor handles alignment, placement and proportions.

  

Back to top

 

 

 

back to top