# Imaging the Web With Scalable Vector Graphics

See the rectangle just above this paragraph? Roll over it with your mouse or pointer. If you are using a relatively contemporary browser, the pointer should turn green and start rotating. This is an example of one of the more powerful technologies on the web that is likely completely invisible to you, whether you’re simply browsing on the web or you’re a web developer wanting to take advantage of your full toolset. It has been a part of the HTML 5 specification for several years now, and especially if you are involved in presenting data to your audience entertainingly or intriguingly, it can hardly be beat. It, in this case, is Scalable Vector Graphics, otherwise known as SVG.

The above SVG is contained inline (for WordPress users, you can include SVG in an HTML Gutenberg block), and appears as follows:


<svg width="120" height="120">
<g transform="translate(60,60)">
<rect width="60" height="60" x="-30" y="-30" id="spinPointer">
<animateTransform  id="spinclockwise" attributeName="transform" attributeType="XML"
type="rotate" to="360" dur="3s" begin="mouseover" end="mouseout"
repeatCount="indefinite" fill="freeze"></animateTransform>
<animateTransform  id="spincclockwise" attributeName="transform" attributeType="XML"
type="rotate" to="0" fill="freeze"
dur="1s" begin="mouseout"></animateTransform>
<animate attributeName="fill" attributeType="CSS" values="green"
begin="spinclockwise.begin" end="spinclockwise.end" repeatCount="indefinite"></animate>
<animate attributeName="fill" attributeType="CSS" values="red"
begin="spincclockwise.begin" end="spincclockwise.end" repeatCount="indefinite"></animate>
</rect>
</g>
</svg>

Typically, however, SVG is normally stored in files, then referenced via the <img> or <image> tag in the same way that a JPEG or PNG file would be referenced (e.g., with the URL of the file referenced by the image’s src attribute). The DSC’s Gutenberg implementation normally means uploading the SVG image into the Media selector as you would any other image. In DSC, such images are displayed inline, which means that the internal contents are affected by scripts and CSS. This can be especially useful when generating buttons and similar interface items.

The scalable nature of SVG is the first and strongest reason for working with the technology. Regardless of how large or small the image is scaled, it will always appear at the highest, crispest resolution. This is especially useful for text, which otherwise blurs when scaled to any significant degree. This is also true for maps and technical illustrations and is indicative of the vector nature of SVG.

Beyond this scalability, SVG images generally tend to be more compact than corresponding bitmap imagery such as PNG or JPEG images (especially the former). Beginning in the early 2010s, most Linux distributions began replacing their bitmap imagery (for icons, buttons, and related entities) with SVG content, and the Windows operating system makes fairly significant use of them from Windows 9 on.

From a web standpoint, HTML5 made SVG a first-class citizen (no need for namespaces) in its 2014 release, causing a cascade as browser vendors released implementations, which was hoped for but seemed a distant dream when the SVG 1.0 specification was first released in 2006. Today, SVG 1.1 is supported (in whole or large part) in every major browser in both desktop and mobile spaces, and has become the standard vector format for embedded systems such as automotive and aircraft displays.

Another key advantage comes from the fact that SVG content is scriptable. This means that content can be animated, respond to user events such as mouse or scroll events, and be manipulated via Javascript in the right environments. This capability is especially powerful when used in conjunction with user interfaces. Many web component libraries are now using SVG to create more complex user interfaces that can be styled with CSS.

## Limitations of SVG

Given all this, and in part because SVG is a very comprehensive specification, there are a few areas here SVG is less than ideal. One notable area has to do with the fact that SVG is a document object model. This means that the model’s whole must be instantiated to render content. This can create heavy-weight DOMs that are memory-intensive for complex objects, especially when used in conjunction with filters and masks. As such, for a while SVG was eschewed in favor of canvas as a mechanism for rendering maps.

However, more recently nVidia and other GPU vendors have begun incorporating SVG path and rendering support into their chip’s graphics capabilities, dramatically speeding up SVG filters, masks, and rendering that tended to be the major bottleneck in performance. SVG in this case may either be rasterized (converted into bitmaps), or paths can be converted at the chip levels into triangulated meshes. Because the SVG path language is very sophisticated (it contains both Bezier and Cubic curve matching), such paths are often preferable for indicating extrusions and intersection determination in 3D. A nice summary of nVIDIA SVG explorations can be found here.

SVG also is more granular in its treatment of text than HTML is. There are advantages to this – SVG text, for instance, is selectable and editable – but HTML is generally better for working with text blocks than SVG. This isn’t a huge limitation, as you can embed HTML within SVG, sometimes to amusing effect, but it’s important to understand how each standard views text content. Additional changes in the SVG 2.0 standard cover areas such as text wrapping and text on paths. At this point, SVG 2.0 is still a candidate recommendation, though with its adoption as a Full Recommendation by the W3C, these features will make SVG much more heavily utilized for layout purposes.

Finally, SVG is not universally supported, though it has made great strides in the last few years. Data visualization libraries such as D3.js migrated away from SVG throughout their development in the 2010s. Still, increasingly these libraries are being refactored for SVG as hardware acceleration of the spec becomes more commonplace.

## SVG Tips and Tricks

The role of this article is not to teach SVG (I’d recommend O’Reilly’s Using SVG with CSS3 and HTML5: Vector Graphics for Web Design, though partially because I’m a co-author), but to touch on a few areas where SVG can be more readily incorporated into your design or development workflow.

### From EPS to SVG

The Encapsulated PostScript format has been a staple for vector clipart for a long time, especially in the desktop publishing arena, and a significant amount of artwork exists. For instance, I retrieved this separator image as an EPS formatted file from StoryBlocks then used CloudConvert‘s excellent converter service to map this to an SVG file, which I can then display directly on this web page:

The graphic at the top of this article was a similar conversion. The same process can be used with Adobe Illustrator files, PDF files, Windows WMF graphics, CAD documents, and other vector formats, usually with little to no lossiness in fidelity or quality. The PDF to SVG conversion, in particular, is notable as it makes it possible to embed PDF documents within web pages without special plugins or adaptors.

### DOT Network Diagrams

I’ve become enamored of online diagram editors – web-based tools that let you quickly make things like Gannt charts, pie charts, network diagrams, etc. Given the degree to which I work with network diagrams, the Graphviz Visual Editor is permanently ensconced as a link on my taskbar. This is most useful for creating DOT network diagrams, a graphics layout language that has been around for more than a decade. The following, for example, illustrates an inheritance diagram that I’m working on for a book on Personal Knowledge Graphs.

 digraph G {
node [style="filled" fillcolor="#C0FFFF"]
edge [fontsize=10 fontname="Arial"]
"Class:_Entity" [label="<Class>\nEntities"]
"Class:_Representation" [label="<Class>\nRepresentations"]
"Class:_Card" [label="<Class>\nCards"]
"Class:_Work" [label="<Class>\nIntellectual Works"]
"Class:_Document" [label="<Class>\nDocuments"]
"Class:_Article" [label="<Class>\nArticles" fillcolor="#80C0FF"]
"Class:_BlogPost" [label="<Class>\nBlogPosts" fillcolor="#80C0FF"]
"Class:_Page" [label="<Class>\nPages" fillcolor="#80C0FF"]
"Class:_LegalEntity" [label="<Class>\nLegal Entities"]
"Class:_NotablePerson" [label="<Class>\nNotablePersons" fillcolor="#80C0FF"]

"Class:_Entity" -> "Class:_Representation" [xlabel="subClassOf"]
"Class:_Representation" -> "Class:_Media" [xlabel="subClassOf"]
"Class:_Media" -> "Class:_Audio" [xlabel="subClassOf"]
"Class:_Media" -> "Class:_Image" [xlabel="subClassOf"]
"Class:_Media" -> "Class:_Video" [xlabel="subClassOf"]
"Class:_Entity" -> "Class:_Card" [xlabel="subClassOf"]
"Class:_Card" -> "Class:_Work" [xlabel="subClassOf"]
"Class:_Work" -> "Class:_Document" [xlabel="subClassOf"]
"Class:_Card" -> "Class:_LegalEntity" [xlabel="subClassOf"]
"Class:_LegalEntity" -> "Class:_Person" [xlabel="subClassOf"]
"Class:_LegalEntity" -> "Class:_Organization" [xlabel="subClassOf"]
"Class:_Document" -> "Class:_Article" [xlabel="subClassOf"]
"Class:_Document" -> "Class:_BlogPost" [xlabel="subClassOf"]
"Class:_Document" -> "Class:_Page" [xlabel="subClassOf"]
"Class:_Person" -> "Class:_Author" [xlabel="subClassOf"]
"Class:_Person" -> "Class:_NotablePerson" [xlabel="subClassOf"]
"Class:_Person" -> "Class:_Character" [xlabel="subClassOf"]
}

and will generate a chart that can be saved as SVG.

It’s worth noting here that if you roll over the <Class>Persons bubble, the cursor will turn to a hyperlink pointer. Clicking on that will then take you the property page for the Schema.org Person class. Even with no scripting, it is possible to turn SVG diagrams into user interface elements trivially.

### SVG and Powerpoint

I use Microsoft Powerpoint heavily in my work – creating lessons, building presentations, incorporating slides for videos, and so forth. If you use the online Office365.com version of Powerpoint, it now supports the importation of PowerPoint as an image format, meaning that you can create a diagram or an illustration in some other tool and then import it directly into a slide as SVG, which is exciting enough.

However, the most recent stand-alone version of PowerPoint goes one step further. You can import the SVG into Powerpoint as an image, where it holds the SVG as a grouped set of Microsoft Draw objects. This means that you can select individual items, move them around, edit the text, and treat them as you would any other Powerpoint shape. What’s more, you can also save Powerpoint documents as sets of zipped SVG documents. For instance, in the diagram below, I loaded the SVG into Powerpoint, ungrouped the shape as draw objects, selected the medium blue classes, changed their color to white text on dark blue background, then saved the page as SVG, before reloading it here:

Visio is another Microsoft product that supports SVG as both an import and output format. One of the biggest problems with building technical documentation has been that many of the graphics formats used for diagrams were in forms that didn’t work well without filters on the web. SVG is rapidly becoming the default for such graphics on the web, making it possible to add not only the imagery, but associated descriptions and metadata into the content, not just at the document level, but at the component level as well.

(It should also be noted that SVG incorporate the <metadata> element, and can inherit the type attribute. The default in the case of SVG is for type is "application/rdf-xml", but there’s nothing specifically stopping the use of JSON-LD or Turtle:

<svg ...>
Prefix Class: <https://www.example.com/Prefix>
...
....
<g id="class_person">
Class:_Person a Owl:Class;
rdfs:label "Persons";
rdfs:subClassOf Class:_LegalEntity;
.
</g>
</svg>      

In this case, it becomes the responsibility of the web application to extract and process this metadata. However, the significance of this is that the images become semantically aware and self-describing at multiple levels of granularity. In the case of an engine, a map of a shopping center, or a diagram showing a process, this, in turn, can hold a huge amount of data in a completely portable manner.

### SVG and Data Analytics

As may be coming obvious, one of the most powerful use cases for SVG is not as a final image format, but as an image interchange format. This can be seen in the number of analytics packages in Python, R and Javascript that all support SVG as both input and output formats. d3.js, which underlies just about every Javascript charting and diagram format, uses SVG heavily, albeit at a fairly low level. The ability to serialize an active chart as an SVG file makes SVG a useful tool with static content and dynamic content.

Python has a number of SVG libraries, including svglib (for SVG input in order to convert to other formats) and PyGal for SVG Generation. Even the hoary matplotlib function can export to SVG (and has been able to do for quite some time).

Similarly, R has the svglite package, which is used to modify the ggplot2 general plotting library to support SVG-based output. These can be tied into report generation pipelines for direct production of dashboards and similar visualization tools.

### Wikipedia and SVG

Finally, it is worth noting that Wikipedia has an extensive number of maps, flags and other resources that are in SVG format, and are remarkably useful for creating heatmaps and and other information graphics. Most of these can be referenced by clicking on subject page vector images to get to the SVG view of the graphics. The following, for instance, was taken from a Wikipedia US Governor’s map, and modified with a bit of XSLT.

As these are Creative Commons, they can be used (and with some work, they can even be used for heat maps or similar constructs). Note, however, that such maps were not originally meant to be manipulated in this manner. So, some experimentation may be called upon before getting too deep into using such maps. Please note that rolling over a state will also show the number of births per thousand for that state, with the lightest having the lowest rates and the darkest having the highest. The file for this map is shown below (states-2), and the source file used for the transformation and is worth studying as it can be readily adapted for different applications.

### Inkscape and Other Graphic Applications

Finally, the open-source Inkscape application is available on most desktop platforms. This tool has been used to build SVG illustrations for over a decade and is a very useful tool for modifying SVGs via a graphical tool. Other tools, including Adobe Illustrator and Corel Draw, have fairly sophisticated SVG export capabilities, but Inkscape should be in every data visualizer’s toolsets.

## Conclusion

Being a good data visualization artist does not necessarily require strong artistic skills, but it does depend upon understanding the tools and technologies that are out there. Scalable Vector Graphics (SVG) is becoming an essential technology in the data space, useful for building maps and charts that can work well on the web, creating detailed diagrams with rich metadata, and even laying the foundation for effective data presentations to clients or customers. SVG really is the foundation for intelligent graphics.