knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(g2r) library(ggplot2)
g2r is an interface to the G2.js JavaScript visualisation library. G2.js is itself a Grammar of Graphics (GG ~= 2G) though some things differ from R's common understanding of such grammar as implemented in ggplot2, some things will be similar to ggplot2 in places.
ggplot2::ggplot
-> g2
ggplot2::aes
-> asp
ggplot2::scale_*
-> gauge_*
ggplot2::geom_*
-> fig_*
ggplot2::facet_*
-> planes_*
ggplot2::theme_*
-> motif_*
The "localisation" or "translation" of the ggplot2 grammar is not just a gimmick it also allows avoiding having one package clash with the other.
Like with ggplot2, one creates visualisations by layering figures (geometries) defined by aspects (aesthetics).
Similarly to ggplot2, axis of the visualisation can be modified with gauge_*
(scales in ggplot2).
As in ggplot2, other aspects of the visualisation can be defined. Unlike ggplot2 though, whether these aspects are columns from the data or constants they can only be specified within asp
.
data(penguins, package = "palmerpenguins")
Where one might use the group
aesthetic in ggplot2 one will want to use color
in g2r; it'll define both the colour and the group.
g2(iris, asp(Petal.Width, color = Species)) %>% fig_density()
In order to stack bars, or place bars side-by-side, or jitter points one must use the adjust
function.
g2(mtcars, asp(mpg, qsec)) %>% fig_point(asp(shape = "circle")) %>% fig_point(adjust("jitter"))
G2r also comes with the equivalent of ggplot2's facets, here they are named planes
.
g2(iris, asp(Sepal.Length, Sepal.Width, color = Species)) %>% fig_point(asp(shape = "circle")) %>% planes(~Species, type = "tree")
There is also a function to quickly draw plots based on the class of the object it receives: qg2
.
s <- stl(nottem, "per") qg2(s)
Generally g2r functions accept data in the form of data.frames or tibbles but it will attempt to transform other objects to (generally) data.frames.
library(forecast) ts <- AirPassengers %>% stlf(lambda=0) g2(ts, asp(x)) %>% fig_line(asp(y = y)) %>% fig_line(asp(y = mean)) %>% fig_ribbon(asp(ymin = lower_80, ymax = upper_80)) %>% fig_ribbon(asp(ymin = lower_95, ymax = upper_95)) %>% tooltip(shared = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.