knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
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)

print(doc)


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)

print(doc)


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)

print(doc)


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)

print(doc)


doc


coolbutuseless/minisvg documentation built on May 2, 2020, 3:15 a.m.