Home icon
Data Visualisation Guide

SVG elements: text

3 minutes read

Online graphics

Vector graphics like SVG have a big advantage over bitmap images: they remain crisp and clear, even when zoomed in. But they have another advantage, related to accessibility: SVG has text elements that you can use to position text in an SVG graphic, and these text elements are accessible to screen readers and search engines.

A PNG image titled A 10 year gap in life expectancy, showing a bar for Norway and one for Bulgaria with their labels

Open this image in a new tab

SVG version of the bar chart

Open this image in a new tab

When Google’s search engine encounters the SVG version of the visualisation above, it will “know” that it is an image about life expectancy in Norway and Bulgaria in 2020, and that the source of the data is Eurostat. For the PNG image, this information should be provided in the alt attribute.

SVG is part of HTML, so adding a <text> element is as easy as adding an opening <text> tag, give it an x and y position in the SVG coordinate system, put the text content in and close the element with </text>.

<svg width="400" height="400" xmlns="http://www.w3.org/2000/svg">
  <text x="100" y="100">Here is some text</text>
	<text x="150" y="150" rotate="20">Text can be rotated...</text>
	<text x="150" y="200" fill="red" font-size="32" font-weight="bold">and also styled</text>
</svg>

text.svg

Source: Maarten Lambrechts, CC-BY-SA 4.0

One thing to keep in mind when using text in SVG is that the user needs to have the font that text elements in the SVG should be displayed in installed on their computer. This is not the case for bitmap images: the text and their font are baked into the JPG or PNG file at the moment they are created. There are ways to embed fonts in SVG files, but a simpler approach is to use web fonts and CSS to apply a font to SVG text elements (see Styling and CSS).

Related pages

HTML and <img>

Styling and CSS

Images in HTML

RAWGraphs

Datawrapper

Flourish

Online graphics