SVG Text

Tutorial

Letter Frequency 0% 20% 40% 60% 80% 100% A B C D E F

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:

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.

AttributeWhat it doesSample Values
font-familySelects the fontFor our uses we'll use just "sans-serif" and "serif".
font-sizeSets the font sizeFor our uses we'll use pixel values such as "12px".
font-weightSets the boldness of the fontFor our uses we'll use "normal" for normal and "bold" for bold.
text-anchorChanges the meaning of the x and y attributesValid 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

Sans-Serif Serif

font-size

Font-Size = 20px Font-Size = 30px

font-weight

normal bold

text-anchor

start (x=100) middle (x=100) end (x=100)

stroke and fill

stroke="darkred" fill="darkblue"

Quiz

Things to do

  1. Use SVG text to add labels to the x-axis (Use consequtive capital letters starting with "A").
  2. Make the label for the longest bar bold.
  3. Add y-axis labels that are right-aligned to the chart. Each line represents 20%, starting with a baseline of 0%.
  4. Add a headline "Word Frequency" to the top of the chart that is San-Serif, 20px tall, and bold

Extra Credit

Change the code on the left. Once you've made a change, the page will render on the right.