Title: | 'Htmlwidget' for 'Vega' and 'Vega-Lite' |
---|---|
Description: | 'Vega' and 'Vega-Lite' parse text in 'JSON' notation to render chart-specifications into 'HTML'. This package is used to facilitate the rendering. It also provides a means to interact with signals, events, and datasets in a 'Vega' chart using 'JavaScript' or 'Shiny'. |
Authors: | Ian Lyttle [aut, cre] , Vega/Vega-Lite Developers [aut], Alicia Schep [ctb] , Stuart Lee [ctb], Kanit Wongsuphasawat [ctb] (Vega/Vega-Lite library), Dominik Moritz [ctb] (Vega/Vega-Lite library), Arvind Satyanarayan [ctb] (Vega/Vega-Lite library), Jeffrey Heer [ctb] (Vega/Vega-Lite library), Mike Bostock [ctb] (D3 library) |
Maintainer: | Ian Lyttle <[email protected]> |
License: | MIT + file LICENSE |
Version: | 0.5.0.9000 |
Built: | 2024-11-12 04:41:38 UTC |
Source: | https://github.com/vegawidget/vegawidget |
Listeners are how we get information out of a Vega chart and into the JavaScript environment. To do this, we specify handler-functions to run whenever a certain signal changes or an event fires.
vw_add_signal_listener(x, name, handler_body) vw_add_data_listener(x, name, handler_body) vw_add_event_listener(x, event, handler_body)
vw_add_signal_listener(x, name, handler_body) vw_add_data_listener(x, name, handler_body) vw_add_event_listener(x, event, handler_body)
x |
vegawidget object to be monitored |
name |
|
handler_body |
|
event |
|
The handler_body
can be the text of the body of a JavaScript function;
the arguments to this function will vary according to the type of listener
you are adding:
signal-handler and data-handler arguments: name
, value
event-handler arguments: event
, item
This package offers some functions to make it easier to build JavaScript
handler functions from R: vw_handler_signal()
, vw_handler_data()
,
and vw_handler_event()
. You can pipe one of these functions to
vw_handler_add_effect()
to perform side-effects on the result.
modified copy of vegawidget object x
vw_handler_signal()
, vw_handler_data()
, vw_handler_event()
,
vw_handler_add_effect()
,
vega-view
Vega and Vega-Lite use JSON as their specification-format. Within R,
it seems natural to work with these specifications as lists. Accordingly,
a vegaspec
is also a list. This family of functions is used to coerce lists,
JSON, and character strings to vegaspec
.
as_vegaspec(spec, ...) ## Default S3 method: as_vegaspec(spec, ...) ## S3 method for class 'vegaspec' as_vegaspec(spec, ...) ## S3 method for class 'list' as_vegaspec(spec, ...) ## S3 method for class 'json' as_vegaspec(spec, ...) ## S3 method for class 'character' as_vegaspec(spec, encoding = "UTF-8", ...) ## S3 method for class 'vegawidget' as_vegaspec(spec, ...)
as_vegaspec(spec, ...) ## Default S3 method: as_vegaspec(spec, ...) ## S3 method for class 'vegaspec' as_vegaspec(spec, ...) ## S3 method for class 'list' as_vegaspec(spec, ...) ## S3 method for class 'json' as_vegaspec(spec, ...) ## S3 method for class 'character' as_vegaspec(spec, encoding = "UTF-8", ...) ## S3 method for class 'vegawidget' as_vegaspec(spec, ...)
spec |
An object to be coerced to |
... |
Other arguments (attempt to future-proof) |
encoding |
|
The character
method for this function will take:
JSON string.
A path to a local JSON file.
A URL that returns a JSON file.
For Vega and Vega-Lite, the translation between lists and JSON is a little
bit particular. This function, as_vegaspec()
, can be used to translate
from JSON; vw_as_json()
can be used to translate to JSON.
You can use the function vw_spec_version()
to determine if a vegaspec
is built for
Vega-Lite or Vega. You can use vw_to_vega()
to translate a Vega-Lite spec to Vega.
An object with S3 class vegaspec
Vega,
Vega-Lite,
vw_as_json()
, vw_spec_version()
, vw_to_vega()
spec <- list( `$schema` = vega_schema(), data = list(values = mtcars), mark = "point", encoding = list( x = list(field = "wt", type = "quantitative"), y = list(field = "mpg", type = "quantitative"), color = list(field = "cyl", type = "nominal") ) ) as_vegaspec(spec) ## Not run: # requires network-access as_vegaspec("https://vega.github.io/vega-lite/examples/specs/bar.vl.json") ## End(Not run)
spec <- list( `$schema` = vega_schema(), data = list(values = mtcars), mark = "point", encoding = list( x = list(field = "wt", type = "quantitative"), y = list(field = "mpg", type = "quantitative"), color = list(field = "cyl", type = "nominal") ) ) as_vegaspec(spec) ## Not run: # requires network-access as_vegaspec("https://vega.github.io/vega-lite/examples/specs/bar.vl.json") ## End(Not run)
This is a toy dataset; the numbers are generated randomly.
data_category
data_category
A data frame with ten observations of two variables
character
, representative of a nominal variable
double
, representative of a quantitative variable
This dataset contains daily weather-observations from Seattle for the years 2012-2015, inclusive.
data_seattle_daily
data_seattle_daily
A data frame with 1461 observations of six variables
Date
, date of the observation
double
, amount of precipitation (mm)
double
, maximum temperature (°C)
double
, minimum temperature (°C)
double
, average wind-speed (m/s)
character
, description of weather
https://vega.github.io/vega-datasets/data/seattle-weather.csv
This dataset contains hourly temperature observations from Seattle for the year 2010.
data_seattle_hourly
data_seattle_hourly
A data frame with 8759 observations of two variables
POSIXct
, instant of the observation, uses "America/Los_Angeles"
double
, temperature (°C)
https://vega.github.io/vega-datasets/data/seattle-weather-hourly-normals.csv
Uses JavaScript notation to interpolate R variables into a string intended to be interpreted as JS.
glue_js(..., .open = "${", .envir = parent.frame())
glue_js(..., .open = "${", .envir = parent.frame())
... |
character vectors as the JavaScript source code (all arguments will be pasted into one character string) |
.open |
|
.envir |
|
This is a wrapper to glue::glue()
, but it uses the notation used by
JavaScript's template-literals,
${}
.
glue::glue()
object
x <- 123 glue_js("function(){return(${x});}") %>% print()
x <- 123 glue_js("function(){return(${x});}") %>% print()
If you have V8,
withr, and fs
installed, you can use these functions can to create
or write images as PNG or SVG, using a vegaspec
or vegawidget
.
To convert to a bitmap, or write a PNG file, you will additionally need
the rsvg and
png packages.
vw_to_svg(spec, width = NULL, height = NULL, base_url = NULL, seed = NULL) vw_to_bitmap(spec, scale = 1, width = NULL, height = NULL, ...) vw_write_svg(spec, path, width = NULL, height = NULL, ...) vw_write_png(spec, path, scale = 1, width = NULL, height = NULL, ...)
vw_to_svg(spec, width = NULL, height = NULL, base_url = NULL, seed = NULL) vw_to_bitmap(spec, scale = 1, width = NULL, height = NULL, ...) vw_write_svg(spec, path, width = NULL, height = NULL, ...) vw_write_png(spec, path, scale = 1, width = NULL, height = NULL, ...)
spec |
An object to be coerced to |
width |
|
height |
|
base_url |
|
seed |
|
scale |
|
... |
additional arguments passed to |
path |
|
These functions can be called using (an object that can be coerced to)
a vegaspec
.
The scripts used are adapted from the Vega command line utilities.
vw_to_svg()
character
, SVG string
vw_to_bitmap()
array
, bitmap array
vw_write_svg()
invisible vegaspec
or vegawidget
, called for side-effects
vw_write_png()
invisible vegaspec
or vegawidget
, called for side-effects
# call any of these functions using either a vegaspec or a vegawidget svg <- vw_to_svg(vegawidget(spec_mtcars)) bmp <- vw_to_bitmap(spec_mtcars) vw_write_png(spec_mtcars, file.path(tempdir(), "temp.png")) vw_write_svg(spec_mtcars, file.path(tempdir(), "temp.svg")) # To specify the path to a local file, use base_url spec_precip <- list( `$schema` = vega_schema(), data = list(url = "seattle-weather.csv"), mark = "tick", encoding = list( x = list(field = "precipitation", type = "quantitative") ) ) %>% as_vegaspec() data_dir <- system.file("example-data/", package = "vegawidget") vw_write_png( spec_precip, file.path(tempdir(), "temp-local.png"), base_url = data_dir )
# call any of these functions using either a vegaspec or a vegawidget svg <- vw_to_svg(vegawidget(spec_mtcars)) bmp <- vw_to_bitmap(spec_mtcars) vw_write_png(spec_mtcars, file.path(tempdir(), "temp.png")) vw_write_svg(spec_mtcars, file.path(tempdir(), "temp.svg")) # To specify the path to a local file, use base_url spec_precip <- list( `$schema` = vega_schema(), data = list(url = "seattle-weather.csv"), mark = "tick", encoding = list( x = list(field = "precipitation", type = "quantitative") ) ) %>% as_vegaspec() data_dir <- system.file("example-data/", package = "vegawidget") vw_write_png( spec_precip, file.path(tempdir(), "temp-local.png"), base_url = data_dir )
If you are knitting to an HTML-based format, the only supported options are
vega.width
, vega.height
(as pixels) and vega.embed
(as a list).
If you are knitting to a non-HTML-based format, you additionally
have the options dev
, out.width
and out.height
available.
knit_print.vegaspec(spec, ..., options = NULL)
knit_print.vegaspec(spec, ..., options = NULL)
spec |
An object to be coerced to |
... |
other arguments |
options |
|
The biggest thing to keep in mind about a Vega visualization is that very often, the chart tells you how much space it needs, rather than than you tell it how much space it has available. In the future, it may reveal itself how to manage better this "conversation".
When knitting to an HTML-based format, the spec
is rendered as normal,
it calls vegawidget()
using the options vega.width
, vega.height
and vega.embed
:
vega.width
and vega.height
are passed to vegawidget()
as width
and height
, respectively. These values are coerced to numeric,
so it is ineffective to specify a percentage. They are passed to
vw_autosize()
to resize the chart, if
possible.
vega.embed
is passed to vegawidget()
as embed
. The function
vega_embed()
can be useful to set vega.embed
.
When knitting to an non-HTML-based format, e.g. github_document
or
pdf_document
, this function will convert the chart to an image, then knitr
will incorporate the image into your document. You have the additional
knitr options dev
, out.width
, and out.height
:
The supported values of dev
are "png"
, "svg"
, and "pdf"
. If you
are knitting to a LaTeX format (e.g. pdf_document
) and you specify dev
as "svg"
, it will be implemented as "pdf"
.
To scale the image within your document, you can use out.width
or
out.height
. Because the image will already have an aspect ratio,
it is recommended to specify no more than one of these.
Use this function in the server part of your Shiny app.
renderVegawidget(expr, env = parent.frame(), quoted = FALSE)
renderVegawidget(expr, env = parent.frame(), quoted = FALSE)
expr |
expression that generates a vegawidget. This can be
a |
env |
The environment in which to evaluate |
quoted |
Is |
There are three types of information you can get from a Vega chart, a signal, data (i.e. a dataset), and information associated with an event. A dataset or a signal must first be defined and named in the vegaspec.
vw_shiny_get_signal(outputId, name, body_value = "value") vw_shiny_get_data(outputId, name, body_value = "value") vw_shiny_get_event(outputId, event, body_value = "datum")
vw_shiny_get_signal(outputId, name, body_value = "value") vw_shiny_get_data(outputId, name, body_value = "value") vw_shiny_get_event(outputId, event, body_value = "datum")
outputId |
|
name |
|
body_value |
|
event |
|
These getter-functions are called from within
a Shiny server()
function, where they act like
shiny::reactive()
, returning a reactive expression.
To see these functions in action, you can run a shiny-demo:
vw_shiny_get_signal()
: call vw_shiny_demo("signal-set-get")
vw_shiny_get_data()
: call vw_shiny_demo("data-set-get")
vw_shiny_get_event()
: call vw_shiny_demo("event-get")
In addition to the chart outputId
, you will need to provide:
vw_shiny_get_signal()
: the name
of the signal, as defined in the Vega
specification
vw_shiny_get_data()
: the name
of the dataset, as defined in the Vega
specification
vw_shiny_get_event()
: the event
type, as defined in the
Vega Event-Stream reference
When the signal or data changes, or when the event fires, Vega needs to know which information you want returned to Shiny. To do this, you provide a JavaScript handler-function:
vw_shiny_get_signal()
: the default handler,
vw_handler_signal("value")
,
specifies that the value of the signal be returned.
vw_shiny_get_data()
: the default handler,
vw_handler_data("value")
,
specifies that the entire dataset be returned.
vw_shiny_get_event()
: the default handler,
vw_handler_event("datum")
,
specifies that the single row of data associated with graphical mark
be returned. For example, if you are monitoring a "click"
event,
Vega would return the row of data that backs any mark
(like a point) that you click.
If you need to specify a different behavior for the handler, there are a
couple of options. This package provides
a library of handler-functions; call vw_handler_signal()
,
vw_handler_data()
, or vw_handler_event()
without arguments to
list the available handlers.
If the library does not contain the handler you need, the body_value
argument will also accept a character string which will be used as
the body of the handler function.
For example, these calls are equivalent:
vw_shiny_get_signal(..., body_value = "value")
vw_shiny_get_signal(..., body_value = vw_handler_signal("value"))
vw_shiny_get_signal(..., body_value = "return value;")
If you use a custom-handler that you think may be useful for the handler-function library, please file an issue.
shiny::reactive()
function that returns the value returned by
body_value
vw_handler_signal()
, vw_handler_event()
,
vega-view:
addSignalListener(),
addEventListener()
There are two ways to change a Vega chart: by setting
a signal or by setting a dataset; you can also
direct a Vega chart to re-run itself. Any signal or
dataset you set must first be defined and named in the vegaspec.
These functions are called from within
a Shiny server()
function, where they act like
shiny::observe()
or shiny::observeEvent()
.
vw_shiny_set_signal(outputId, name, value, run = TRUE, ...) vw_shiny_set_data(outputId, name, value, run = TRUE, ...) vw_shiny_run(outputId, value, ...)
vw_shiny_set_signal(outputId, name, value, run = TRUE, ...) vw_shiny_set_data(outputId, name, value, run = TRUE, ...) vw_shiny_run(outputId, value, ...)
outputId |
|
name |
|
value |
reactive expression, e.g. |
run |
|
... |
other arguments passed on to |
To see these functions in action, you can run a shiny-demo:
vw_shiny_set_signal()
: call vw_shiny_demo("signal-set-get")
vw_shiny_set_data()
: call vw_shiny_demo("data-set-get")
vw_shiny_run()
: call vw_shiny_demo("data-set-swap-run")
For the signal and data setters, in addition to the chart outputId
,
you will need to provide:
the name
of the signal or dataset you wish to keep updated
the value
to which you want to set the signal or dataset;
this should be a reactive expression like input$slider
or rct_dataset()
whether or not you want to run
the Vega view again immediately
after setting this value
If you do not set run = TRUE
in the setter-function,
you can use the vw_shiny_run()
function to control when
the chart re-runs. One possibility is to set its value
to a reactive
expression that refers to, for example, a shiny::actionButton()
.
shiny::observeEvent()
function that responds to changes in the
reactive-expression value
A Vega-Lite specification to create a scatterplot for mtcars
.
spec_mtcars
spec_mtcars
S3 object of class vegaspec
These functions are offered to help you import and re-export vegawidget functions in your package. For more detail, please see this article.
use_vegawidget(s3_class_name = NULL) use_vegawidget_interactive()
use_vegawidget(s3_class_name = NULL) use_vegawidget_interactive()
s3_class_name |
|
use_vegawidget()
:
Adds vegawidget functions:
format()
, print()
, knit_print()
vw_to_svg()
and other image functions
In practical terms:
adds vegawidget to Imports
in your package's DESCRIPTION file.
adds V8, withr, fs, rsvg, and png to Suggests
in your package's DESCRIPTION file.
creates R/utils-vegawidget.R
you can delete references to functions you do not want to re-export.
If you have your own S3 class for a spec, specify the s3_class_name
argument. You will have to edit R/utils-vegawidget-<s3_class_name>.R
:
add the code within your class's method for
to coerce your object to a vegaspec
.
To permit knit-printing of your custom class, you will have to add some code
to your package's .onLoad()
function.
use_vegawidget_interactive()
:
If you want to add the JavaScript and Shiny functions,
use this after running use_vegawidget()
. It adds:
vw_add_data_listener()
and other listener-functions.
vw_handler_data()
and other handler functions.
vw_shiny_get_data()
and other Shiny getters.
vw_shiny_set_data()
and other Shiny setters.
In practical terms:
adds shiny, dplyr, to Suggests
.
creates R/utils-vegawidget-interactive.R
.
at your discretion, delete references to functions you do not want to re-export.
invisible NULL
, called for side effects
Helper-function to specify the embed
argument to vegawidget()
.
These arguments reflect the options to the
vega-embed
library, which ultimately renders the chart specification as HTML.
vega_embed( renderer = c("canvas", "svg"), actions = NULL, defaultStyle = TRUE, config = NULL, patch = NULL, bind = NULL, ... )
vega_embed( renderer = c("canvas", "svg"), actions = NULL, defaultStyle = TRUE, config = NULL, patch = NULL, bind = NULL, ... )
renderer |
|
actions |
|
defaultStyle |
|
config |
|
patch |
|
bind |
|
... |
other named items, outlined in vega-embed options. |
The most important arguments are renderer
, actions
, and defaultStyle
:
The default renderer
is "canvas"
.
The default for actions
is NULL
, which means that the export
,
source
, and editor
links are shown, but the compiled
link is
not shown.
To suppress all action links, call with actions = FALSE
.
To change from the default for a given action link, call with a list:
actions = list(editor = FALSE)
.
The default for defaultStyle
is TRUE
, which means that action-links
are rendered in a widget at the upper-right corner of the rendered chart.
The vega-embed library has a lot
more options, you can supply these as names arguments using ...
.
For example, it is ineffective to set the width
and height
parameters
here when embedding a Vega-Lite specification, as they will be overridden
by the value in the chart specification.
list
to to be used with vega-embed JavaScript library
vega-embed library,
vegawidget()
vega_embed(renderer = "svg")
vega_embed(renderer = "svg")
Useful if you are creating a vegaspec manually.
vega_schema( library = c("vega_lite", "vega"), version = NULL, major = is.null(version) )
vega_schema( library = c("vega_lite", "vega"), version = NULL, major = is.null(version) )
library |
|
version |
|
major |
|
character
URL for schema
vega_schema() vega_schema("vega", major = FALSE) vega_schema("vega_lite", version = "5.2.0") # creating a spec by hand spec <- list( `$schema` = vega_schema(), width = 300, height = 300 # and so on ) %>% as_vegaspec()
vega_schema() vega_schema("vega", major = FALSE) vega_schema("vega_lite", version = "5.2.0") # creating a spec by hand spec <- list( `$schema` = vega_schema(), width = 300, height = 300 # and so on ) %>% as_vegaspec()
Use these functions to get which versions of Vega JavaScript libraries
are available. vega_version_all()
returns a data frame showing all
versions included in this package, vega_version_available()
returns
all versions available - subject to locking,
vega_version()
shows the default version.
vega_version(major = FALSE) vega_version_all(major = FALSE) vega_version_available(major = FALSE)
vega_version(major = FALSE) vega_version_all(major = FALSE) vega_version_available(major = FALSE)
major |
|
This package offers multiple widgets, each corresponding to a major version
of Vega-Lite. Only one of these widgets can be used for a given loading of
this package. When vegawidget()
is first called, the widget is "locked"
according to the $schema
in the vegaspec
used, or the default - the
most-recent version.
is_locked
indicates if vegawidget()
is has locked the version.
widget
indicates which version of the widget would be used.
list
with elements: is_locked
, widget
,
vega_lite
, vega
, vega_embed
.
data.frame
with elements: widget
,
vega_lite
, vega
, vega_embed
.
data.frame
with elements: widget
,
vega_lite
, vega
, vega_embed
.
vega_version() vega_version(major = TRUE) vega_version_all() vega_version_available()
vega_version() vega_version(major = TRUE) vega_version_all() vega_version_available()
The main use of this package is to render a vegawidget
,
which is also an htmlwidget
. This function builds a vegawidget
using a vegaspec
.
vegawidget( spec, embed = NULL, width = NULL, height = NULL, elementId = NULL, base_url = NULL, ... )
vegawidget( spec, embed = NULL, width = NULL, height = NULL, elementId = NULL, base_url = NULL, ... )
spec |
An object to be coerced to |
embed |
|
width |
|
height |
|
elementId |
|
base_url |
|
... |
other arguments passed to |
If embed
is NULL
, vegawidget()
uses:
getOption("vega.embed")
, if that is NULL:
an empty call to vega_embed()
The most-important arguments to vega_embed()
are:
renderer
, to specify "canvas"
(default) or "svg"
actions
, to specify action-links
for export
, source
, compiled
, and editor
If either width
or height
is specified, the autosize()
function
is used to override the width and height of the spec
. There are some
important provisions:
Specifying width
and height
is
effective only for single-view charts and layered charts.
It will not work for concatenated, faceted, or repeated charts.
In the spec
, the default interpretation of width and height
is to describe the dimensions of the
plotting rectangle, not including the space used by the axes, labels,
etc. Here, width
and height
describe the dimensions
of the entire rendered chart, including axes, labels, etc.
Please note that if you are using a remote URL to refer to a dataset in your vegaspec, it may not render properly in the RStudio IDE, due to a security policy set by RStudio. If you open the chart in a browser, it should render properly.
S3 object of class vegawidget
and htmlwidget
vega-embed options,
vega_embed()
, vw_autosize()
vegawidget(spec_mtcars, width = 350, height = 350) # vegaspec with a data URL spec_precip <- list( `$schema` = vega_schema(), data = list(url = "seattle-weather.csv"), mark = "tick", encoding = list( x = list(field = "precipitation", type = "quantitative") ) ) %>% as_vegaspec() # define local path to file path_local <- system.file("example-data", package = "vegawidget") # render using local path (does not work with knitr) vegawidget(spec_precip, base_url = path_local) ## Not run: # requires network-access # define remote path to file url_remote <- "https://vega.github.io/vega-datasets/data" # render using remote path # note: does not render in RStudio IDE; open using browser vegawidget(spec_precip, base_url = url_remote) ## End(Not run)
vegawidget(spec_mtcars, width = 350, height = 350) # vegaspec with a data URL spec_precip <- list( `$schema` = vega_schema(), data = list(url = "seattle-weather.csv"), mark = "tick", encoding = list( x = list(field = "precipitation", type = "quantitative") ) ) %>% as_vegaspec() # define local path to file path_local <- system.file("example-data", package = "vegawidget") # render using local path (does not work with knitr) vegawidget(spec_precip, base_url = path_local) ## Not run: # requires network-access # define remote path to file url_remote <- "https://vega.github.io/vega-datasets/data" # render using remote path # note: does not render in RStudio IDE; open using browser vegawidget(spec_precip, base_url = url_remote) ## End(Not run)
Use this function in the UI part of your Shiny app.
vegawidgetOutput(outputId, width = "auto", height = "auto", widget = NULL)
vegawidgetOutput(outputId, width = "auto", height = "auto", widget = NULL)
outputId |
output variable to read from |
width , height
|
Must be a valid CSS unit (like |
widget |
|
For Vega and Vega-Lite, the translation between lists and JSON is a little
bit particular. This function, vw_as_json()
, can be used to translate
to JSON; as_vegaspec()
can be used to translate from JSON.
vw_as_json(spec, pretty = TRUE)
vw_as_json(spec, pretty = TRUE)
spec |
An object to be coerced to |
pretty |
|
jsonlite::json
object
vw_as_json(spec_mtcars)
vw_as_json(spec_mtcars)
The arguments width
and height
are used to override the width and height
of the provided spec
, if the spec
does not have multiple views.
The dimensions you provide describe the overall width and height of the
rendered chart, including axes, labels, legends, etc.
vw_autosize(spec, width = NULL, height = NULL)
vw_autosize(spec, width = NULL, height = NULL)
spec |
An object to be coerced to |
width |
|
height |
|
In a Vega or Vega-Lite specification, the default interpretation
of width and height is to describe the dimensions of the
data rectangle, not including the space used by the axes, labels,
legends, etc. When width
and height
are specified using
autosize,
the meanings of width
and height
change to describe the dimensions
of the entire chart, including axes, labels, legends, etc.
There is an important limitation: specifying width
and height
is
effective only for single-view and layered specifications.
It will not work for specifications with multiple views
(e.g. hconcat
, vconcat
, facet
, repeat
); this will issue a
warning that there will be no effect on the specification when rendered.
S3 object with class vegaspec
Article on vegaspec (sizing), Vega documentation on sizing
vw_autosize(spec_mtcars, width = 350, height = 350)
vw_autosize(spec_mtcars, width = 350, height = 350)
This is a thin wrapper to listviewer::jsonedit()
,
use to interactively examine a Vega or Vega-Lite specification.
vw_examine( spec, mode = "view", modes = c("view", "code", "form", "text", "tree"), ..., width = NULL, height = NULL, elementId = NULL )
vw_examine( spec, mode = "view", modes = c("view", "code", "form", "text", "tree"), ..., width = NULL, height = NULL, elementId = NULL )
spec |
An object to be coerced to |
mode |
|
modes |
string |
... |
|
width |
integer in pixels defining the width of the |
height |
integer in pixels defining the height of the |
elementId |
character to specify valid |
S3 object of class jsonedit
and htmlwidget
vw_examine(spec_mtcars) spec_mtcars_autosize <- spec_mtcars %>% vw_autosize(width = 300, height = 300) vw_examine(spec_mtcars_autosize)
vw_examine(spec_mtcars) spec_mtcars_autosize <- spec_mtcars %>% vw_autosize(width = 300, height = 300) vw_examine(spec_mtcars_autosize)
With a JavaScript handler, once you have calculated a value
based on the handler's arguments (e.g. name
, value
) you will
likely want to produce a side-effect based on that calculated value.
This function helps you do that.
vw_handler_add_effect(vw_handler, body_effect, ...)
vw_handler_add_effect(vw_handler, body_effect, ...)
vw_handler |
|
body_effect |
|
... |
additional named parameters to be interpolated into the text of the handler_body |
The calculation of a value is meant to be separate from the production of a side-effect. This way, the code for a side-effect can be used for any type of handler.
You are supplying the body_effect
to an effect-handler. This
takes a single argument, x
, representing the
calculated value. Doing this allows us to chain side-effects together;
be careful not to modify x
in any of the code you provide.
To see what side-effects are available in this package's handler-library,
call vw_handler_add_effect()
without any arguments. You may notice that
some of the effects, like "element_text"
, require additional parameters,
in this case, selector
.
Those parameters with a default value of NULL
require you to supply
a value; those with sensible defaults are optional.
To provide the parameters, call
vw_handler_add_effect()
with named arguments corresponding to the
names of the parameters. See the examples for details.
modified copy of vw_handler
# list all the available effect-handlers vw_handler_add_effect() # build a signal handler that prints some text, # then the value, to the console vw_handler_signal("value") %>% vw_handler_add_effect("console", label = "signal value:")
# list all the available effect-handlers vw_handler_add_effect() # build a signal handler that prints some text, # then the value, to the console vw_handler_signal("value") %>% vw_handler_add_effect("console", label = "signal value:")
A Vega listener needs a JavaScript handler-function to call
when the object-being-listened-to changes. For instance, shiny-getters and
add-listeners functions each have an argument called
body_value
, which these functions help you build.
vw_handler_signal(body_value) vw_handler_data(body_value) vw_handler_event(body_value)
vw_handler_signal(body_value) vw_handler_data(body_value) vw_handler_event(body_value)
body_value |
|
There are two types of handlers defined in this package's handler-library. To see the handlers that are defined for each, call the function without any arguments:
vw_handler_signal()
vw_handler_data()
vw_handler_event()
With a JavaScript handler, you are trying to do two types of things:
calculate a value based on the handler's arguments
produce a side-effect based on that calculated value
Let's look at a concrete example.
A signal handler
will take arguments name
and value
. Let's say that we want to
return the value. We could do this two ways:
vw_handler_signal("value")
: use this package's handler library
vw_handler_signal("return value;")
: supply the body of the
handler-function yourself
In the list above, the two calls do exactly the same thing, they build a
JavaScript function that returns the value
provided by whatever is calling
the signal-handler. This will be a valid signal-handler, however, we will
likely want a signal-handler to do something with that value, which is
why we may wish to add a side-effect.
Let's say we want the handler to print the value to the JavaScript console. We would create the signal-handler, then add an effect to print the result to the console.
vw_handler_signal("value") %>% vw_handler_add_effect("console")
We can add as many effects as we like; for more information,
please see the documentation for vw_handler_add_effect()
.
Please be aware that these functions do not check for the correctness of JavaScript code you supply - any errors you make will not be apparent until your visualization is rendered in a browser.
One last note, if body_value
is already a vw_handler
, these functions
are no-ops; they will return the body_value
unchanged.
object with S3 class vw_handler
vw_handler_add_effect()
,
vega-view
# list all the available signal-handlers vw_handler_signal() # list all the available data-handlers vw_handler_data() # list all the available event-handlers vw_handler_event() # use a defined signal-handler vw_handler_signal("value") # define your own signal-handler vw_handler_signal("return value;")
# list all the available signal-handlers vw_handler_signal() # list all the available data-handlers vw_handler_data() # list all the available event-handlers vw_handler_event() # use a defined signal-handler vw_handler_signal("value") # define your own signal-handler vw_handler_signal("return value;")
If a vegaspec has named datasets, it may be useful to rename them.
This function will return a vegaspec with datasets named data_001
,
data_002
, and so on. It will go through the spec and replace the
references to the names. A future version of this function may give you
the more control over the names used.
vw_rename_datasets(spec)
vw_rename_datasets(spec)
spec |
An object to be coerced to |
S3 object of class vegaspec
Please think of this as an experimental function
vw_serialize_data(data, iso_dttm = FALSE, iso_date = TRUE)
vw_serialize_data(data, iso_dttm = FALSE, iso_date = TRUE)
data |
|
iso_dttm |
|
iso_date |
|
In Vega, for now, there are only two time-zones available: the local
time-zone of the browser where the spec is rendered, and UTC. This differs
from R, where a time-zone attribute is available to POSIXct
vectors.
Accordingly, when designing a vegaspec that uses time, you have to make some
some compromises. This function helps you to implement your compromise in
a principled way, as explained in the opinions below.
Let's assume that your POSIXct
data has a time-zone attached.
There are three different scenarios for rendering this data:
using the time-zone of the browser
using UTC
using the time-zone of the data
If you intend to display the data using the time-zone of the browser,
or using UTC, you should serialize datetimes using ISO-8601, i.e.
iso_dttm = TRUE
. In the rest of your vegaspec, you should choose
local or UTC time-scales accordingly. However, in either case, you should
use local time-units. No compromise is necessary.
If you intend to display the data using the time-zone of the browser,
this is where you will have to compromise. In this case, you should
serialize using iso_dttm = FALSE
. By doing this, your datetimes will be
serialized using a non-ISO-8601 format, and notably, using the time-zone
of the datetime. When you design your vegaspec, you should treat this as
if it were a UTC time. You should direct Vega to parse this data as UTC,
i.e. {"foo": "utc:'%Y-%m-%d %H:%M:%S'"}
. In other words, Vega should
interpret your local timestamp as if it were a UTC timestamp.
As in the first UTC case, you should use UTC time-scales and local
time-units.
The compromise you are making is this: the internal representation of
the instants in time will be different in Vega than it will be in R.
You are losing information because you are converting from a POSIXct
object with a time-zone to a timestamp without a time-zone. It is also
worth noting that the time information in your Vega plot should not
be used anywhere else - this should be the last place this serialized
data should be used because it is no longer trustworthy. For this,
you will gain the ability to show the data in the context of its
time-zone.
Dates can be different creatures than datetimes. I think that can be "common currency" for dates. I think this is because it is more common to compare across different locations using dates as a common index. For example, you might compare daily stock-market data from NYSE, CAC-40, and Hang Seng. To maintain a common time-index, you might choose UTC to represent the dates in all three locations, despite the time-zone differences.
This is why the default for iso_date
is TRUE
. In this scenario,
you need not specify to Vega how to parse the date; because of its
ISO-8601 format, it will parse to UTC. As with the other UTC cases,
you should use UTC time-scales and local time-units.
object with the same type as data
# datetimes data_seattle_hourly %>% head() data_seattle_hourly %>% head() %>% vw_serialize_data(iso_dttm = TRUE) data_seattle_hourly %>% head() %>% vw_serialize_data(iso_dttm = FALSE) # dates data_seattle_daily %>% head() data_seattle_daily %>% head() %>% vw_serialize_data(iso_date = TRUE) data_seattle_daily %>% head() %>% vw_serialize_data(iso_date = FALSE)
# datetimes data_seattle_hourly %>% head() data_seattle_hourly %>% head() %>% vw_serialize_data(iso_dttm = TRUE) data_seattle_hourly %>% head() %>% vw_serialize_data(iso_dttm = FALSE) # dates data_seattle_daily %>% head() data_seattle_daily %>% head() %>% vw_serialize_data(iso_date = TRUE) data_seattle_daily %>% head() %>% vw_serialize_data(iso_date = FALSE)
This is useful for specs where data is specified using a URL. Using this function to set the base URL, you can specify the data URL in specs using the relative path from the base.
For example, this
Vega-Lite example
uses the base URL https://cdn.jsdelivr.net/npm/vega-datasets@2
. In a spec,
instead of specifying:
data = "https://cdn.jsdelivr.net/npm/vega-datasets@2/data/cars.json"
You can call:
vw_set_base_url("https://cdn.jsdelivr.net/npm/vega-datasets@2")
Then specify:
data = "data/cars.json"
This function sets the value of getOption("vega-embed")$loader$baseURL
.
You need set it only once in a session or RMarkdown file.
vw_set_base_url(url)
vw_set_base_url(url)
url |
|
character
called for side effects, it returns the previous value
invisibly.
# this is the URL used for Vega datasets previous <- vw_set_base_url("https://cdn.jsdelivr.net/npm/vega-datasets@2") # reset to previous value vw_set_base_url(previous)
# this is the URL used for Vega datasets previous <- vw_set_base_url("https://cdn.jsdelivr.net/npm/vega-datasets@2") # reset to previous value vw_set_base_url(previous)
Run Shiny demonstration-apps
vw_shiny_demo(example = NULL, ...)
vw_shiny_demo(example = NULL, ...)
example |
|
... |
additional arguments passed to |
invisible NULL, called for side-effects
vw_shiny_demo() # returns available examples # Run only in interactive R sessions if (interactive()) { vw_shiny_demo("data-set-get") }
vw_shiny_demo() # returns available examples # Run only in interactive R sessions if (interactive()) { vw_shiny_demo("data-set-get") }
Use this function to determine the library
and version
of a vegaspec
.
vw_spec_version(spec)
vw_spec_version(spec)
spec |
An object to be coerced to |
Returns a list with two elements:
library
character
, either "vega"
or "vega_lite"
version
character
, version tag
list
with elements library
, version
vw_spec_version(spec_mtcars) # vw_to_vega() requires the V8 package vw_spec_version(vw_to_vega(spec_mtcars))
vw_spec_version(spec_mtcars) # vw_to_vega() requires the V8 package vw_spec_version(vw_to_vega(spec_mtcars))
If you have V8 installed, you can use this function to compile a Vega-Lite specification into a Vega specification.
vw_to_vega(spec)
vw_to_vega(spec)
spec |
An object to be coerced to |
S3 object of class vegaspec_vega
and vegaspec
vw_spec_version(spec_mtcars) vw_spec_version(vw_to_vega(spec_mtcars))
vw_spec_version(spec_mtcars) vw_spec_version(vw_to_vega(spec_mtcars))