SVG Text
Tutorial
The charts from the last chapter were unusual because they did not have labels indicating what values the bars or lines stood for. Most visual displays of quantitative data have text labels. The chart above displays the same data as in the previous chapter but this time with axis labels. The axis labels make it much easier to determine the values encoded in the chart. Since we're using SVG, we need to know how to place text in SVG graphics.
How to create SVG text
SVG text is created with the <text> element within an SVG region. The required attributes of a text element are:
- x - the text's x coordinate. By default it refers to the left-most edge of the text.
- y - the text's y coordinate. By default it refers to the bottom of the text.
For example, the text "Hello World" is created with SVG is created like this: <text x="10" y="20">Hello World</text>
How to style SVG text
For our purposes we'll be concerned with simple adjustments such as which font, the font size, if it's bold or not, and how to align it with other visual elements. Below is a reference table for how to make these adjustments.
Attribute | What it does | Sample Values |
---|---|---|
font-family | Selects the font | For our uses we'll use just "sans-serif" and "serif". |
font-size | Sets the font size | For our uses we'll use pixel values such as "12px". |
font-weight | Sets the boldness of the font | For our uses we'll use "normal" for normal and "bold" for bold. |
text-anchor | Changes the meaning of the x and y attributes | Valid values are "start", "middle", and "end". These mean that x refers to the beginning of the text, the center of the text, or the end of the text respectively. At the start of this chapter we used "end" for the y-axis and "start" for the x-axis. |
In addition, stroke and fill color the text outline and filling color respectively, as they do for all SVG elements.
Below are examples of the various options above.
font-family
font-size
font-weight
text-anchor
stroke and fill
Quiz
Things to do
- Use SVG text to add labels to the x-axis (Use consequtive capital letters starting with "A").
- Make the label for the longest bar bold.
- Add y-axis labels that are right-aligned to the chart. Each line represents 20%, starting with a baseline of 0%.
- Add a headline "Word Frequency" to the top of the chart that is San-Serif, 20px tall, and bold
Extra Credit
- The SVG 1.1 standard does not support automatic text wrapping. Use an internet search to learn about ways to work around this.