library(minisvg)

Introduction

The SVG tags for <polygon> and <polyline> require a points argument which represents the coordinates of the vertices as a single string e.g. “0,0 0,1 1,1 1,0”.

This is a little awkward to do from R, so the creation of polygons and polylines have some alternate methods for specifying vertices.

How to create a polygon or polyline

  1. Using stag. E.g. stag$polygon(...)
  2. Using SVGElement$new('polygon', ...)
  3. Adding to an exisint element with elem$add('polygon', ...)

Using points

The actual SVG points argument for <polygon> and <polyline> is a single string of the form x0,y0 x1,y1 x2,y2 ...

doc <- svg_doc(width=150, height=150)
doc$add('polygon', points = "0,0 100,0 100,100 0,100", fill = 'blue')

Show SVG text (click to open)

#> <?xml version="1.0" encoding="UTF-8"?>
#> <svg width="150" height="150" viewBox="0 0 150 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
#>   <polygon points="0,0 100,0 100,100 0,100" fill="blue" />
#> </svg>


doc

Using xs and ys

Can use xs and ys numeric vectors which contain the coordinates.

xs <- c(0, 100, 100, 0)
ys <- c(0, 0, 100, 100)

doc <- svg_doc(width=150, height=150)
doc$add('polygon', xs = xs, ys = ys, fill = 'green')

Show SVG text (click to open)

#> <?xml version="1.0" encoding="UTF-8"?>
#> <svg width="150" height="150" viewBox="0 0 150 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
#>   <polygon points="0,0 100,0 100,100 0,100" fill="green" />
#> </svg>


doc

Using xs as a data.frame

xs can be a data.frame with x and y numeric columns representing the coorindates.

coords_df <- data.frame(
  x = c(0, 100, 100, 0),
  y = c(0, 0, 100, 100)
)

doc <- svg_doc(width=150, height=150)
doc$add('polygon', xs = coords_df, fill = 'pink')

Show SVG text (click to open)

#> <?xml version="1.0" encoding="UTF-8"?>
#> <svg width="150" height="150" viewBox="0 0 150 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
#>   <polygon points="0,0 100,0 100,100 0,100" fill="pink" />
#> </svg>


doc

Using xs as a matrix

xs can be a matrix with the first 2 columns representing the coorindates.

coords_mat <- matrix(c(
  0, 100, 100, 0,
  0, 0, 100, 100),
  ncol = 2
)

doc <- svg_doc(width=150, height=150)
doc$add('polygon', xs = coords_df, fill = 'orange')

Show SVG text (click to open)

#> <?xml version="1.0" encoding="UTF-8"?>
#> <svg width="150" height="150" viewBox="0 0 150 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
#>   <polygon points="0,0 100,0 100,100 0,100" fill="orange" />
#> </svg>


doc