I am trying to create a SVG polyline graph from values within my XML doc. So far I have produced the chart but I am unable to correctly retrieve the values from the XML doc. Below is the current state of the graph:
The graph is intended to display average monthly weather temperatures so should therefore be lower at the edges and a peak in the centre.
Here is my XML code:
<xml>
<graph2>
<averageHighTemperatures>
<January>8.3</January>
<February>8.5</February>
<March>11.1</March>
<April>13.5</April>
<May>17.1</May>
<June>20.0</June>
<July>22.6</July>
<August>22.5</August>
<September>19.3</September>
<October>15.3</October>
<November>11.2</November>
<December>9.1</December>
</averageHighTemperatures>
</graph2>
</xml>
Here is my XSL code:
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 500 100" class="chart">
<xsl:variable name="max">
<xsl:for-each select="xml/graph2/averageHighTemperatures/*">
<xsl:sort select="." data-type="number" order="descending"/><xsl:if test="position()=1">
<xsl:value-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
<xsl:for-each select="xml/graph2/averageHighTemperatures">
<polyline
fill="none"
stroke="#0074d9"
stroke-width="3"
points="0,{January div $max}
20,{February div $max}
40,{March div $max}
60,{April div $max}
80,{May div $max}
100,{June div $max}
120,{July div $max}
140,{August div $max}
160,{September div $max}
180,{October div $max}
200,{November div $max}
220,{December div $max}"/>
</xsl:for-each>
</svg>
I assume that the XSL for each loop at the bottom is the source of the issue but I am unsure how to use the variable correctly when plotting the points.
Thanks in advance
In an SVG chart,
0,0
is at the top left. Smaller Y values will plot at the top, and larger Y values will move towards the bottom.So, for your temperature line, the highest temperature should have the lowest number for the Y axis. You could divide the temperature value by the maximum and then multiple by 100, and then subtract that from the height of the chart. Since you have a
stroke-width
, the line for the highest numbers might get cut off, so you might want to account for that in the calculation of the values.This is how I would generate your linechart:
Which renders as: