Title: | Create Interactive Web Graphics via 'plotly.js' |
---|---|
Description: | Create interactive web graphics from 'ggplot2' graphs and/or a custom interface to the (MIT-licensed) JavaScript library 'plotly.js' inspired by the grammar of graphics. |
Authors: | Carson Sievert [aut, cre] , Chris Parmer [aut], Toby Hocking [aut], Scott Chamberlain [aut], Karthik Ram [aut], Marianne Corvellec [aut] , Pedro Despouy [aut], Salim Brüggemann [ctb] , Plotly Technologies Inc. [cph] |
Maintainer: | Carson Sievert <[email protected]> |
License: | MIT + file LICENSE |
Version: | 4.10.4.9000 |
Built: | 2024-10-27 05:51:16 UTC |
Source: | https://github.com/plotly/plotly.r |
Add an annotation(s) to a plot
add_annotations(p, text = NULL, ..., data = NULL, inherit = TRUE)
add_annotations(p, text = NULL, ..., data = NULL, inherit = TRUE)
p |
a plotly object |
text |
annotation text (required). |
... |
these arguments are documented at https://github.com/plotly/plotly.js/blob/master/src/components/annotations/attributes.js |
data |
a data frame. |
inherit |
inherit attributes from |
Carson Sievert
Add data to a plotly visualization
add_data(p, data = NULL)
add_data(p, data = NULL)
p |
a plotly visualization |
data |
a data frame. |
plot_ly() %>% add_data(economics) %>% add_trace(x = ~date, y = ~pce)
plot_ly() %>% add_data(economics) %>% add_trace(x = ~date, y = ~pce)
Useful when you need two or more layers that apply a summary statistic to the original data.
add_fun(p, fun, ...)
add_fun(p, fun, ...)
p |
a plotly object. |
fun |
a function. Should take a plotly object as input and return a modified plotly object. |
... |
arguments passed to |
Add trace(s) to a plotly visualization
add_trace(p, ..., data = NULL, inherit = TRUE) add_markers(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_text( p, x = NULL, y = NULL, z = NULL, text = NULL, ..., data = NULL, inherit = TRUE ) add_paths(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_lines(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_segments( p, x = NULL, y = NULL, xend = NULL, yend = NULL, ..., data = NULL, inherit = TRUE ) add_polygons(p, x = NULL, y = NULL, ..., data = NULL, inherit = TRUE) add_sf(p, ..., x = ~x, y = ~y, data = NULL, inherit = TRUE) add_table(p, ..., rownames = TRUE, data = NULL, inherit = TRUE) add_ribbons( p, x = NULL, ymin = NULL, ymax = NULL, ..., data = NULL, inherit = TRUE ) add_image(p, z = NULL, colormodel = NULL, ..., data = NULL, inherit = TRUE) add_area(p, r = NULL, theta = NULL, t = NULL, ..., data = NULL, inherit = TRUE) add_pie(p, values = NULL, labels = NULL, ..., data = NULL, inherit = TRUE) add_bars(p, x = NULL, y = NULL, ..., data = NULL, inherit = TRUE) add_histogram(p, x = NULL, y = NULL, ..., data = NULL, inherit = TRUE) add_histogram2d( p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE ) add_histogram2dcontour( p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE ) add_heatmap(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_contour(p, z = NULL, ..., data = NULL, inherit = TRUE) add_boxplot(p, x = NULL, y = NULL, ..., data = NULL, inherit = TRUE) add_surface(p, z = NULL, ..., data = NULL, inherit = TRUE) add_mesh(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_scattergeo(p, ...) add_choropleth(p, z = NULL, ..., data = NULL, inherit = TRUE)
add_trace(p, ..., data = NULL, inherit = TRUE) add_markers(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_text( p, x = NULL, y = NULL, z = NULL, text = NULL, ..., data = NULL, inherit = TRUE ) add_paths(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_lines(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_segments( p, x = NULL, y = NULL, xend = NULL, yend = NULL, ..., data = NULL, inherit = TRUE ) add_polygons(p, x = NULL, y = NULL, ..., data = NULL, inherit = TRUE) add_sf(p, ..., x = ~x, y = ~y, data = NULL, inherit = TRUE) add_table(p, ..., rownames = TRUE, data = NULL, inherit = TRUE) add_ribbons( p, x = NULL, ymin = NULL, ymax = NULL, ..., data = NULL, inherit = TRUE ) add_image(p, z = NULL, colormodel = NULL, ..., data = NULL, inherit = TRUE) add_area(p, r = NULL, theta = NULL, t = NULL, ..., data = NULL, inherit = TRUE) add_pie(p, values = NULL, labels = NULL, ..., data = NULL, inherit = TRUE) add_bars(p, x = NULL, y = NULL, ..., data = NULL, inherit = TRUE) add_histogram(p, x = NULL, y = NULL, ..., data = NULL, inherit = TRUE) add_histogram2d( p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE ) add_histogram2dcontour( p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE ) add_heatmap(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_contour(p, z = NULL, ..., data = NULL, inherit = TRUE) add_boxplot(p, x = NULL, y = NULL, ..., data = NULL, inherit = TRUE) add_surface(p, z = NULL, ..., data = NULL, inherit = TRUE) add_mesh(p, x = NULL, y = NULL, z = NULL, ..., data = NULL, inherit = TRUE) add_scattergeo(p, ...) add_choropleth(p, z = NULL, ..., data = NULL, inherit = TRUE)
p |
a plotly object |
... |
Arguments (i.e., attributes) passed along to the trace |
data |
A data frame (optional) or crosstalk::SharedData object. |
inherit |
inherit attributes from |
x |
the x variable. |
y |
the y variable. |
z |
a numeric matrix (unless |
text |
textual labels. |
xend |
"final" x position (in this context, x represents "start") |
yend |
"final" y position (in this context, y represents "start") |
rownames |
whether or not to display the rownames of |
ymin |
a variable used to define the lower boundary of a polygon. |
ymax |
a variable used to define the upper boundary of a polygon. |
colormodel |
Sets the colormodel for image traces if |
r |
Sets the radial coordinates. |
theta |
Sets the angular coordinates. |
t |
Deprecated. Use |
values |
the value to associated with each slice of the pie. |
labels |
the labels (categories) corresponding to |
Carson Sievert
https://plotly-r.com/overview.html
https://plotly.com/r/reference/
# the `plot_ly()` function initiates an object, and if no trace type # is specified, it sets a sensible default p <- plot_ly(economics, x = ~date, y = ~uempmed) p # some `add_*()` functions are a specific case of a trace type # for example, `add_markers()` is a scatter trace with mode of markers add_markers(p) # scatter trace with mode of text add_text(p, text = "%") # scatter trace with mode of lines add_paths(p) # like `add_paths()`, but ensures points are connected according to `x` add_lines(p) # if you prefer to work with plotly.js more directly, can always # use `add_trace()` and specify the type yourself add_trace(p, type = "scatter", mode = "markers+lines") # mappings provided to `plot_ly()` are "global", but can be overwritten plot_ly(economics, x = ~date, y = ~uempmed, color = I("red"), showlegend = FALSE) %>% add_lines() %>% add_markers(color = ~pop) # a number of `add_*()` functions are special cases of the scatter trace plot_ly(economics, x = ~date) %>% add_ribbons(ymin = ~pce - 1e3, ymax = ~pce + 1e3) # use `group_by()` (or `group2NA()`) to apply visual mapping # once per group (e.g. one line per group) txhousing %>% group_by(city) %>% plot_ly(x = ~date, y = ~median) %>% add_lines(color = I("black")) ## Not run: # use `add_sf()` or `add_polygons()` to create geo-spatial maps # http://blog.cpsievert.me/2018/03/30/visualizing-geo-spatial-data-with-sf-and-plotly/ if (requireNamespace("sf", quietly = TRUE)) { nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE) plot_ly() %>% add_sf(data = nc) } # univariate summary statistics plot_ly(mtcars, x = ~factor(vs), y = ~mpg) %>% add_boxplot() plot_ly(mtcars, x = ~factor(vs), y = ~mpg) %>% add_trace(type = "violin") # `add_histogram()` does binning for you... mtcars %>% plot_ly(x = ~factor(vs)) %>% add_histogram() # ...but you can 'pre-compute' bar heights in R mtcars %>% dplyr::count(vs) %>% plot_ly(x = ~vs, y = ~n) %>% add_bars() # the 2d analogy of add_histogram() is add_histogram2d()/add_histogram2dcontour() library(MASS) (p <- plot_ly(geyser, x = ~waiting, y = ~duration)) add_histogram2d(p) add_histogram2dcontour(p) # the 2d analogy of add_bars() is add_heatmap()/add_contour() # (i.e., bin counts must be pre-specified) den <- kde2d(geyser$waiting, geyser$duration) p <- plot_ly(x = den$x, y = den$y, z = den$z) add_heatmap(p) add_contour(p) # `add_table()` makes it easy to map a data frame to the table trace type plot_ly(economics) %>% add_table() # pie charts! ds <- data.frame(labels = c("A", "B", "C"), values = c(10, 40, 60)) plot_ly(ds, labels = ~labels, values = ~values) %>% add_pie() %>% layout(title = "Basic Pie Chart using Plotly") data(wind) plot_ly(wind, r = ~r, theta = ~t) %>% add_area(color = ~nms) %>% layout( polar = list( radialaxis = list(ticksuffix = "%"), angularaxis = list(rotation = 90) ) ) # ------------------------------------------------------------ # 3D chart types # ------------------------------------------------------------ plot_ly(z = ~volcano) %>% add_surface() plot_ly(x = c(0, 0, 1), y = c(0, 1, 0), z = c(0, 0, 0)) %>% add_mesh() ## End(Not run)
# the `plot_ly()` function initiates an object, and if no trace type # is specified, it sets a sensible default p <- plot_ly(economics, x = ~date, y = ~uempmed) p # some `add_*()` functions are a specific case of a trace type # for example, `add_markers()` is a scatter trace with mode of markers add_markers(p) # scatter trace with mode of text add_text(p, text = "%") # scatter trace with mode of lines add_paths(p) # like `add_paths()`, but ensures points are connected according to `x` add_lines(p) # if you prefer to work with plotly.js more directly, can always # use `add_trace()` and specify the type yourself add_trace(p, type = "scatter", mode = "markers+lines") # mappings provided to `plot_ly()` are "global", but can be overwritten plot_ly(economics, x = ~date, y = ~uempmed, color = I("red"), showlegend = FALSE) %>% add_lines() %>% add_markers(color = ~pop) # a number of `add_*()` functions are special cases of the scatter trace plot_ly(economics, x = ~date) %>% add_ribbons(ymin = ~pce - 1e3, ymax = ~pce + 1e3) # use `group_by()` (or `group2NA()`) to apply visual mapping # once per group (e.g. one line per group) txhousing %>% group_by(city) %>% plot_ly(x = ~date, y = ~median) %>% add_lines(color = I("black")) ## Not run: # use `add_sf()` or `add_polygons()` to create geo-spatial maps # http://blog.cpsievert.me/2018/03/30/visualizing-geo-spatial-data-with-sf-and-plotly/ if (requireNamespace("sf", quietly = TRUE)) { nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE) plot_ly() %>% add_sf(data = nc) } # univariate summary statistics plot_ly(mtcars, x = ~factor(vs), y = ~mpg) %>% add_boxplot() plot_ly(mtcars, x = ~factor(vs), y = ~mpg) %>% add_trace(type = "violin") # `add_histogram()` does binning for you... mtcars %>% plot_ly(x = ~factor(vs)) %>% add_histogram() # ...but you can 'pre-compute' bar heights in R mtcars %>% dplyr::count(vs) %>% plot_ly(x = ~vs, y = ~n) %>% add_bars() # the 2d analogy of add_histogram() is add_histogram2d()/add_histogram2dcontour() library(MASS) (p <- plot_ly(geyser, x = ~waiting, y = ~duration)) add_histogram2d(p) add_histogram2dcontour(p) # the 2d analogy of add_bars() is add_heatmap()/add_contour() # (i.e., bin counts must be pre-specified) den <- kde2d(geyser$waiting, geyser$duration) p <- plot_ly(x = den$x, y = den$y, z = den$z) add_heatmap(p) add_contour(p) # `add_table()` makes it easy to map a data frame to the table trace type plot_ly(economics) %>% add_table() # pie charts! ds <- data.frame(labels = c("A", "B", "C"), values = c(10, 40, 60)) plot_ly(ds, labels = ~labels, values = ~values) %>% add_pie() %>% layout(title = "Basic Pie Chart using Plotly") data(wind) plot_ly(wind, r = ~r, theta = ~t) %>% add_area(color = ~nms) %>% layout( polar = list( radialaxis = list(ticksuffix = "%"), angularaxis = list(rotation = 90) ) ) # ------------------------------------------------------------ # 3D chart types # ------------------------------------------------------------ plot_ly(z = ~volcano) %>% add_surface() plot_ly(x = c(0, 0, 1), y = c(0, 1, 0), z = c(0, 0, 0)) %>% add_mesh() ## End(Not run)
Animations can be created by either using the frame
argument in
plot_ly()
or the (unofficial) frame
ggplot2 aesthetic in
ggplotly()
. By default, animations populate a play button
and slider component for controlling the state of the animation
(to pause an animation, click on a relevant location on the slider bar).
Both the play button and slider component transition between frames according
rules specified by animation_opts()
.
animation_opts( p, frame = 500, transition = frame, easing = "linear", redraw = TRUE, mode = "immediate" ) animation_slider(p, hide = FALSE, ...) animation_button(p, ..., label)
animation_opts( p, frame = 500, transition = frame, easing = "linear", redraw = TRUE, mode = "immediate" ) animation_slider(p, hide = FALSE, ...) animation_button(p, ..., label)
p |
a plotly object. |
frame |
The amount of time between frames (in milliseconds).
Note that this amount should include the |
transition |
The duration of the smooth transition between frames (in milliseconds). |
easing |
The type of transition easing. See the list of options here https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js |
redraw |
Trigger a redraw of the plot at completion of the transition? A redraw may significantly impact performance, but may be necessary to update graphical elements that can't be transitioned. |
mode |
Describes how a new animate call interacts with currently-running
animations. If |
hide |
remove the animation slider? |
... |
for |
label |
a character string used for the animation button's label |
Carson Sievert
df <- data.frame( x = c(1, 2, 2, 1, 1, 2), y = c(1, 2, 2, 1, 1, 2), z = c(1, 1, 2, 2, 3, 3) ) plot_ly(df) %>% add_markers(x = 1.5, y = 1.5) %>% add_markers(x = ~x, y = ~y, frame = ~z) # it's a good idea to remove smooth transitions when there is # no relationship between objects in each view plot_ly(mtcars, x = ~wt, y = ~mpg, frame = ~cyl) %>% animation_opts(transition = 0) # works the same way with ggplotly if (interactive()) { p <- ggplot(txhousing, aes(month, median)) + geom_line(aes(group = year), alpha = 0.3) + geom_smooth() + geom_line(aes(frame = year, ids = month), color = "red") + facet_wrap(~ city) ggplotly(p, width = 1200, height = 900) %>% animation_opts(1000) } #' # for more, see https://plotly.com/r/animating-views.html
df <- data.frame( x = c(1, 2, 2, 1, 1, 2), y = c(1, 2, 2, 1, 1, 2), z = c(1, 1, 2, 2, 3, 3) ) plot_ly(df) %>% add_markers(x = 1.5, y = 1.5) %>% add_markers(x = ~x, y = ~y, frame = ~z) # it's a good idea to remove smooth transitions when there is # no relationship between objects in each view plot_ly(mtcars, x = ~wt, y = ~mpg, frame = ~cyl) %>% animation_opts(transition = 0) # works the same way with ggplotly if (interactive()) { p <- ggplot(txhousing, aes(month, median)) + geom_line(aes(group = year), alpha = 0.3) + geom_smooth() + geom_line(aes(frame = year, ids = month), color = "red") + facet_wrap(~ city) ggplotly(p, width = 1200, height = 900) %>% animation_opts(1000) } #' # for more, see https://plotly.com/r/animating-views.html
Convenience functions for working with version 2 of plotly's REST API.
Upload R objects to a plotly account via api_create()
and download
plotly objects via api_download_plot()
/api_download_grid()
.
For anything else, use api()
.
api_create( x = last_plot(), filename = NULL, fileopt = c("overwrite", "new"), sharing = c("public", "private", "secret"), ... ) ## S3 method for class 'plotly' api_create( x = last_plot(), filename = NULL, fileopt = "overwrite", sharing = "public", ... ) ## S3 method for class 'ggplot' api_create( x = last_plot(), filename = NULL, fileopt = "overwrite", sharing = "public", ... ) ## S3 method for class 'data.frame' api_create(x, filename = NULL, fileopt = "overwrite", sharing = "public", ...) api_download_plot(id, username) api_download_grid(id, username) api(endpoint = "/", verb = "GET", body = NULL, ...)
api_create( x = last_plot(), filename = NULL, fileopt = c("overwrite", "new"), sharing = c("public", "private", "secret"), ... ) ## S3 method for class 'plotly' api_create( x = last_plot(), filename = NULL, fileopt = "overwrite", sharing = "public", ... ) ## S3 method for class 'ggplot' api_create( x = last_plot(), filename = NULL, fileopt = "overwrite", sharing = "public", ... ) ## S3 method for class 'data.frame' api_create(x, filename = NULL, fileopt = "overwrite", sharing = "public", ...) api_download_plot(id, username) api_download_grid(id, username) api(endpoint = "/", verb = "GET", body = NULL, ...)
x |
An R object to hosted on plotly's web platform. Can be a plotly/ggplot2 object or a data.frame. |
filename |
character vector naming file(s). If |
fileopt |
character string describing whether to "overwrite" existing files or ensure "new" file(s) are always created. |
sharing |
If 'public', anyone can view this graph. It will appear in your profile and can appear in search engines. You do not need to be logged in to Plotly to view this chart. If 'private', only you can view this plot. It will not appear in the Plotly feed, your profile, or search engines. You must be logged in to Plotly to view this graph. You can privately share this graph with other Plotly users in your online Plotly account and they will need to be logged in to view this plot. If 'secret', anyone with this secret link can view this chart. It will not appear in the Plotly feed, your profile, or search engines. If it is embedded inside a webpage or an IPython notebook, anybody who is viewing that page will be able to view the graph. You do not need to be logged in to view this plot. |
... |
For |
id |
a filename id. |
username |
a plotly username. |
endpoint |
the endpoint (i.e., location) for the request.
To see a list of all available endpoints, call |
verb |
name of the HTTP verb to use (as in, |
body |
body of the HTTP request(as in, |
Carson Sievert
## Not run: # ------------------------------------------------------------ # api_create() makes it easy to upload ggplot2/plotly objects # and/or data frames to your plotly account # ------------------------------------------------------------ # A data frame creates a plotly "grid". Printing one will take you # to the it's web address so you can start creating! (m <- api_create(mtcars)) # A plotly/ggplot2 object create a plotly "plot". p <- plot_ly(mtcars, x = ~factor(vs)) (r <- api_create(p)) # api_create() returns metadata about the remote "file". Here is # one way you could use that metadata to download a plot for local use: fileID <- strsplit(r$file$fid, ":")[[1]] layout( api_download_plot(fileID[2], fileID[1]), title = sprintf("Local version of <a href='%s'>this</a> plot", r$file$web_url) ) ------------------------------------------------------------ # The api() function provides a low-level interface for performing # any action at any endpoint! It always returns a list. # ------------------------------------------------------------ # list all the endpoints api() # search the entire platform! # see https://api.plot.ly/v2/search api("search?q=overdose") api("search?q=plottype:pie trump fake") # these examples will require a user account usr <- Sys.getenv("plotly_username", NA) if (!is.na(usr)) { # your account info https://api.plot.ly/v2/#users api(sprintf("users/%s", usr)) # your folders/files https://api.plot.ly/v2/folders#user api(sprintf("folders/home?user=%s", usr)) } # Retrieve a specific file https://api.plot.ly/v2/files#retrieve api("files/cpsievert:14681") # change the filename https://api.plot.ly/v2/files#update # (note: this won't work unless you have proper credentials to the relevant account) api("files/cpsievert:14681", "PATCH", list(filename = "toy file")) # Copy a file https://api.plot.ly/v2/files#lookup api("files/cpsievert:14681/copy", "POST") # Create a folder https://api.plot.ly/v2/folders#create api("folders", "POST", list(path = "/starts/at/root/and/ends/here")) ## End(Not run)
## Not run: # ------------------------------------------------------------ # api_create() makes it easy to upload ggplot2/plotly objects # and/or data frames to your plotly account # ------------------------------------------------------------ # A data frame creates a plotly "grid". Printing one will take you # to the it's web address so you can start creating! (m <- api_create(mtcars)) # A plotly/ggplot2 object create a plotly "plot". p <- plot_ly(mtcars, x = ~factor(vs)) (r <- api_create(p)) # api_create() returns metadata about the remote "file". Here is # one way you could use that metadata to download a plot for local use: fileID <- strsplit(r$file$fid, ":")[[1]] layout( api_download_plot(fileID[2], fileID[1]), title = sprintf("Local version of <a href='%s'>this</a> plot", r$file$web_url) ) ------------------------------------------------------------ # The api() function provides a low-level interface for performing # any action at any endpoint! It always returns a list. # ------------------------------------------------------------ # list all the endpoints api() # search the entire platform! # see https://api.plot.ly/v2/search api("search?q=overdose") api("search?q=plottype:pie trump fake") # these examples will require a user account usr <- Sys.getenv("plotly_username", NA) if (!is.na(usr)) { # your account info https://api.plot.ly/v2/#users api(sprintf("users/%s", usr)) # your folders/files https://api.plot.ly/v2/folders#user api(sprintf("folders/home?user=%s", usr)) } # Retrieve a specific file https://api.plot.ly/v2/files#retrieve api("files/cpsievert:14681") # change the filename https://api.plot.ly/v2/files#update # (note: this won't work unless you have proper credentials to the relevant account) api("files/cpsievert:14681", "PATCH", list(filename = "toy file")) # Copy a file https://api.plot.ly/v2/files#lookup api("files/cpsievert:14681/copy", "POST") # Create a folder https://api.plot.ly/v2/folders#create api("folders", "POST", list(path = "/starts/at/root/and/ends/here")) ## End(Not run)
Convert a list to a plotly htmlwidget object
as_widget(x, ...)
as_widget(x, ...)
x |
a plotly object. |
... |
other options passed onto |
trace <- list(x = 1, y = 1) obj <- list(data = list(trace), layout = list(title = "my plot")) as_widget(obj)
trace <- list(x = 1, y = 1) obj <- list(data = list(trace), layout = list(title = "my plot")) as_widget(obj)
This function was deprecated in 4.0.0, as plotly objects are now htmlwidget objects, so there is no need to convert them.
as.widget(x, ...)
as.widget(x, ...)
x |
a plotly object. |
... |
other options passed onto |
By default the name of the selection trace derives from the selected values.
attrs_selected(opacity = 1, ...)
attrs_selected(opacity = 1, ...)
opacity |
a number between 0 and 1 specifying the overall opacity of the selected trace |
... |
other trace attributes attached to the selection trace. |
Carson Sievert
Estimate bounding box of a rotated string
bbox(txt = "foo", angle = 0, size = 12)
bbox(txt = "foo", angle = 0, size = 12)
txt |
a character string of length 1 |
angle |
sets the angle of the tick labels with respect to the
horizontal (e.g., |
size |
vertical size of a character |
https://www.dropbox.com/s/nc6968prgw8ne4w/bbox.pdf?dl=0
Modify the colorbar
colorbar(p, ..., limits = NULL, which = 1)
colorbar(p, ..., limits = NULL, which = 1)
p |
a plotly object |
... |
arguments are documented here https://plotly.com/r/reference/#scatter-marker-colorbar. |
limits |
numeric vector of length 2. Set the extent of the colorbar scale. |
which |
colorbar to modify? Should only be relevant for subplots with multiple colorbars. |
Carson Sievert
p <- plot_ly(mtcars, x = ~wt, y = ~mpg, color = ~cyl) # pass any colorbar attribute -- # https://plotly.com/r/reference/#scatter-marker-colorbar colorbar(p, len = 0.5) # Expand the limits of the colorbar colorbar(p, limits = c(0, 20)) # values outside the colorbar limits are considered "missing" colorbar(p, limits = c(5, 6)) # also works on colorbars generated via a z value corr <- cor(diamonds[vapply(diamonds, is.numeric, logical(1))]) plot_ly(x = rownames(corr), y = colnames(corr), z = corr) %>% add_heatmap() %>% colorbar(limits = c(-1, 1))
p <- plot_ly(mtcars, x = ~wt, y = ~mpg, color = ~cyl) # pass any colorbar attribute -- # https://plotly.com/r/reference/#scatter-marker-colorbar colorbar(p, len = 0.5) # Expand the limits of the colorbar colorbar(p, limits = c(0, 20)) # values outside the colorbar limits are considered "missing" colorbar(p, limits = c(5, 6)) # also works on colorbars generated via a z value corr <- cor(diamonds[vapply(diamonds, is.numeric, logical(1))]) plot_ly(x = rownames(corr), y = colnames(corr), z = corr) %>% add_heatmap() %>% colorbar(limits = c(-1, 1))
Set the default configuration for plotly
config( p, ..., cloud = FALSE, showSendToCloud = cloud, locale = NULL, mathjax = NULL )
config( p, ..., cloud = FALSE, showSendToCloud = cloud, locale = NULL, mathjax = NULL )
p |
a plotly object |
... |
these arguments are documented at https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js |
cloud |
deprecated. Use |
showSendToCloud |
include the send data to cloud button? |
locale |
locale to use. See here for more info. |
mathjax |
add MathJax rendering support.
If |
Carson Sievert
# remove the plotly logo and collaborate button from modebar config(plot_ly(), displaylogo = FALSE, collaborate = FALSE) # enable mathjax # see more examples at https://plotly.com/r/LaTeX/ plot_ly(x = c(1, 2, 3, 4), y = c(1, 4, 9, 16)) %>% layout(title = TeX("\\text{Some mathjax: }\\alpha+\\beta x")) %>% config(mathjax = "cdn") # change the language used to render date axes and on-graph text # (e.g., modebar buttons) today <- Sys.Date() x <- seq.Date(today, today + 360, by = "day") p <- plot_ly(x = x, y = rnorm(length(x))) %>% add_lines() # japanese config(p, locale = "ja") # german config(p, locale = "de") # spanish config(p, locale = "es") # chinese config(p, locale = "zh-CN")
# remove the plotly logo and collaborate button from modebar config(plot_ly(), displaylogo = FALSE, collaborate = FALSE) # enable mathjax # see more examples at https://plotly.com/r/LaTeX/ plot_ly(x = c(1, 2, 3, 4), y = c(1, 4, 9, 16)) %>% layout(title = TeX("\\text{Some mathjax: }\\alpha+\\beta x")) %>% config(mathjax = "cdn") # change the language used to render date axes and on-graph text # (e.g., modebar buttons) today <- Sys.Date() x <- seq.Date(today, today + 360, by = "day") p <- plot_ly(x = x, y = rnorm(length(x))) %>% add_lines() # japanese config(p, locale = "ja") # german config(p, locale = "de") # spanish config(p, locale = "es") # chinese config(p, locale = "zh-CN")
Embed a plot as an iframe into a Jupyter Notebook
embed_notebook(x, width = NULL, height = NULL, file = NULL)
embed_notebook(x, width = NULL, height = NULL, file = NULL)
x |
a plotly object |
width |
attribute of the iframe. If |
height |
attribute of the iframe. If |
file |
deprecated. |
Carson Sievert
This function must be called within a reactive shiny context.
event_data( event = c("plotly_hover", "plotly_unhover", "plotly_click", "plotly_doubleclick", "plotly_selected", "plotly_selecting", "plotly_brushed", "plotly_brushing", "plotly_deselect", "plotly_relayout", "plotly_restyle", "plotly_legendclick", "plotly_legenddoubleclick", "plotly_clickannotation", "plotly_afterplot", "plotly_sunburstclick"), source = "A", session = shiny::getDefaultReactiveDomain(), priority = c("input", "event") )
event_data( event = c("plotly_hover", "plotly_unhover", "plotly_click", "plotly_doubleclick", "plotly_selected", "plotly_selecting", "plotly_brushed", "plotly_brushing", "plotly_deselect", "plotly_relayout", "plotly_restyle", "plotly_legendclick", "plotly_legenddoubleclick", "plotly_clickannotation", "plotly_afterplot", "plotly_sunburstclick"), source = "A", session = shiny::getDefaultReactiveDomain(), priority = c("input", "event") )
event |
The type of plotly event. All supported events are listed in the function signature above (i.e., the usage section). |
source |
a character string of length 1. Match the value of this string
with the |
session |
a shiny session object (the default should almost always be used). |
priority |
the priority of the corresponding shiny input value.
If equal to |
Carson Sievert
event_register, event_unregister
## Not run: plotly_example("shiny", "event_data") ## End(Not run)
## Not run: plotly_example("shiny", "event_data") ## End(Not run)
Register a shiny input value
event_register(p, event = NULL)
event_register(p, event = NULL)
p |
a plotly object. |
event |
The type of plotly event. All supported events are listed in the function signature above (i.e., the usage section). |
Carson Sievert
Un-register a shiny input value
event_unregister(p, event = NULL)
event_unregister(p, event = NULL)
p |
a plotly object. |
event |
The type of plotly event. All supported events are listed in the function signature above (i.e., the usage section). |
Carson Sievert
This function is deprecated, use save_image instead.
export(p = last_plot(), file = "plotly.png", selenium = NULL, ...)
export(p = last_plot(), file = "plotly.png", selenium = NULL, ...)
p |
a plotly or ggplot object. |
file |
a filename. The file type is inferred from the file extension. Valid extensions include 'jpeg' | 'png' | 'webp' | 'svg' | 'pdf' |
selenium |
used only when |
... |
if |
For SVG plots, a screenshot is taken via webshot::webshot()
.
Since phantomjs
(and hence webshot
) does not support WebGL,
the RSelenium package is used for exporting WebGL plots.
Carson Sievert
This function makes it possible to convert ggplot2 geoms that are not included with ggplot2 itself. Users shouldn't need to use this function. It exists purely to allow other package authors to write their own conversion method(s).
geom2trace(data, params, p)
geom2trace(data, params, p)
data |
the data returned by |
params |
parameters for the geom, statistic, and 'constant' aesthetics |
p |
a ggplot2 object (the conversion may depend on scales, for instance). |
Deprecated: see api_download_plot()
.
get_figure(username, id)
get_figure(username, id)
username |
corresponding username for the figure. |
id |
of the Plotly figure. |
Convert a ggplot to a list.
gg2list( p, width = NULL, height = NULL, tooltip = "all", dynamicTicks = FALSE, layerData = 1, originalData = TRUE, source = "A", ... )
gg2list( p, width = NULL, height = NULL, tooltip = "all", dynamicTicks = FALSE, layerData = 1, originalData = TRUE, source = "A", ... )
p |
ggplot2 plot. |
width |
Width of the plot in pixels (optional, defaults to automatic sizing). |
height |
Height of the plot in pixels (optional, defaults to automatic sizing). |
tooltip |
a character vector specifying which aesthetic tooltips to show in the tooltip. The default, "all", means show all the aesthetic tooltips (including the unofficial "text" aesthetic). |
dynamicTicks |
accepts the following values: |
layerData |
data from which layer should be returned? |
originalData |
should the "original" or "scaled" data be returned? |
source |
a character string of length 1. Match the value of this string
with the source argument in |
... |
currently not used |
a 'built' plotly object (list with names "data" and "layout").
This function converts a ggplot2::ggplot()
object to a
plotly object.
ggplotly( p = ggplot2::last_plot(), width = NULL, height = NULL, tooltip = "all", dynamicTicks = FALSE, layerData = 1, originalData = TRUE, source = "A", ... )
ggplotly( p = ggplot2::last_plot(), width = NULL, height = NULL, tooltip = "all", dynamicTicks = FALSE, layerData = 1, originalData = TRUE, source = "A", ... )
p |
a ggplot object. |
width |
Width of the plot in pixels (optional, defaults to automatic sizing). |
height |
Height of the plot in pixels (optional, defaults to automatic sizing). |
tooltip |
a character vector specifying which aesthetic mappings to show
in the tooltip. The default, "all", means show all the aesthetic mappings
(including the unofficial "text" aesthetic). The order of variables here will
also control the order they appear. For example, use
|
dynamicTicks |
should plotly.js dynamically generate axis tick labels? Dynamic ticks are useful for updating ticks in response to zoom/pan interactions; however, they can not always reproduce labels as they would appear in the static ggplot2 image. |
layerData |
data from which layer should be returned? |
originalData |
should the "original" or "scaled" data be returned? |
source |
a character string of length 1. Match the value of this string
with the source argument in |
... |
arguments passed onto methods. |
Conversion of relative sizes depends on the size of the current
graphics device (if no device is open, width/height of a new (off-screen)
device defaults to 640/480). In other words, height
and
width
must be specified at runtime to ensure sizing is correct.
For examples on how to specify the output container's height
/width
in a
shiny app, see plotly_example("shiny", "ggplotly_sizing")
.
Carson Sievert
## Not run: # simple example ggpenguins <- qplot(bill_length_mm , body_mass_g, data = palmerpenguins::penguins, color = species) ggplotly(ggpenguins) data(canada.cities, package = "maps") viz <- ggplot(canada.cities, aes(long, lat)) + borders(regions = "canada") + coord_equal() + geom_point(aes(text = name, size = pop), colour = "red", alpha = 1/2) ggplotly(viz, tooltip = c("text", "size")) # linked scatterplot brushing d <- highlight_key(mtcars) qplot(data = d, x = mpg, y = wt) %>% subplot(qplot(data = d, x = mpg, y = vs)) %>% layout(title = "Click and drag to select points") %>% highlight("plotly_selected") # more brushing (i.e. highlighting) examples demo("crosstalk-highlight-ggplotly", package = "plotly") # client-side linked brushing in a scatterplot matrix highlight_key(palmerpenguins::penguins) %>% GGally::ggpairs(aes(colour = Species), columns = 1:4) %>% ggplotly(tooltip = c("x", "y", "colour")) %>% highlight("plotly_selected") ## End(Not run)
## Not run: # simple example ggpenguins <- qplot(bill_length_mm , body_mass_g, data = palmerpenguins::penguins, color = species) ggplotly(ggpenguins) data(canada.cities, package = "maps") viz <- ggplot(canada.cities, aes(long, lat)) + borders(regions = "canada") + coord_equal() + geom_point(aes(text = name, size = pop), colour = "red", alpha = 1/2) ggplotly(viz, tooltip = c("text", "size")) # linked scatterplot brushing d <- highlight_key(mtcars) qplot(data = d, x = mpg, y = wt) %>% subplot(qplot(data = d, x = mpg, y = vs)) %>% layout(title = "Click and drag to select points") %>% highlight("plotly_selected") # more brushing (i.e. highlighting) examples demo("crosstalk-highlight-ggplotly", package = "plotly") # client-side linked brushing in a scatterplot matrix highlight_key(palmerpenguins::penguins) %>% GGally::ggpairs(aes(colour = Species), columns = 1:4) %>% ggplotly(tooltip = c("x", "y", "colour")) %>% highlight("plotly_selected") ## End(Not run)
This function is used internally by plotly, but may also be useful to some power users. The details section explains when and why this function is useful.
group2NA( data, groupNames = "group", nested = NULL, ordered = NULL, retrace.first = inherits(data, "GeomPolygon") )
group2NA( data, groupNames = "group", nested = NULL, ordered = NULL, retrace.first = inherits(data, "GeomPolygon") )
data |
a data frame. |
groupNames |
character vector of grouping variable(s) |
nested |
other variables that group should be nested (i.e., ordered) within. |
ordered |
a variable to arrange by (within nested & groupNames). This is useful primarily for ordering by x |
retrace.first |
should the first row of each group be appended to the last row? This is useful for enclosing polygons with lines. |
If a group of scatter traces share the same non-positional characteristics
(i.e., color, fill, etc), it is more efficient to draw them as a single trace
with missing values that separate the groups (instead of multiple traces),
In this case, one should also take care to make sure
connectgaps
is set to FALSE
.
a data.frame with rows ordered by: nested
,
then groupNames
, then ordered
. As long as groupNames
contains valid variable names, new rows will also be inserted to separate
the groups.
# note the insertion of new rows with missing values group2NA(mtcars, "vs", "cyl") # need to group lines by city somehow! plot_ly(txhousing, x = ~date, y = ~median) %>% add_lines() # instead of using group_by(), you could use group2NA() tx <- group2NA(txhousing, "city") plot_ly(tx, x = ~date, y = ~median) %>% add_lines() # add_lines() will ensure paths are sorted by x, but this is equivalent tx <- group2NA(txhousing, "city", ordered = "date") plot_ly(tx, x = ~date, y = ~median) %>% add_paths()
# note the insertion of new rows with missing values group2NA(mtcars, "vs", "cyl") # need to group lines by city somehow! plot_ly(txhousing, x = ~date, y = ~median) %>% add_lines() # instead of using group_by(), you could use group2NA() tx <- group2NA(txhousing, "city") plot_ly(tx, x = ~date, y = ~median) %>% add_lines() # add_lines() will ensure paths are sorted by x, but this is equivalent tx <- group2NA(txhousing, "city", ordered = "date") plot_ly(tx, x = ~date, y = ~median) %>% add_paths()
Hide color bar(s)
hide_colorbar(p)
hide_colorbar(p)
p |
a plotly object. |
p <- plot_ly(mtcars, x = ~wt, y = ~cyl, color = ~cyl) hide_colorbar(p)
p <- plot_ly(mtcars, x = ~wt, y = ~cyl, color = ~cyl) hide_colorbar(p)
Hide guides (legends and colorbars)
hide_guides(p)
hide_guides(p)
p |
a plotly object. |
hide_legend()
, hide_colorbar()
Hide legend
hide_legend(p)
hide_legend(p)
p |
a plotly object. |
p <- plot_ly(mtcars, x = ~wt, y = ~cyl, color = ~factor(cyl)) hide_legend(p)
p <- plot_ly(mtcars, x = ~wt, y = ~cyl, color = ~factor(cyl)) hide_legend(p)
This function sets a variety of options for brushing (i.e., highlighting)
multiple plots. These options are primarily designed for linking
multiple plotly graphs, and may not behave as expected when linking
plotly to another htmlwidget package via crosstalk. In some cases,
other htmlwidgets will respect these options, such as persistent selection
in leaflet (see demo("highlight-leaflet", package = "plotly")
).
highlight( p, on = "plotly_click", off, persistent = getOption("persistent", FALSE), dynamic = FALSE, color = NULL, selectize = FALSE, defaultValues = NULL, opacityDim = getOption("opacityDim", 0.2), selected = attrs_selected(), debounce = 0, ... )
highlight( p, on = "plotly_click", off, persistent = getOption("persistent", FALSE), dynamic = FALSE, color = NULL, selectize = FALSE, defaultValues = NULL, opacityDim = getOption("opacityDim", 0.2), selected = attrs_selected(), debounce = 0, ... )
p |
a plotly visualization. |
on |
turn on a selection on which event(s)? To disable on events
altogether, use
|
off |
turn off a selection on which event(s)? To disable off
events altogether, use
|
persistent |
should selections persist (i.e., accumulate)? We often
refer to the default ( |
dynamic |
should a widget for changing selection colors be included? |
color |
character string of color(s) to use for
highlighting selections. See |
selectize |
whether or not to render a selectize.js widget for selecting
|
defaultValues |
a vector of values for setting a "default selection". These values should match the key attribute. |
opacityDim |
a number between 0 and 1 used to reduce the opacity of non-selected traces (by multiplying with the existing opacity). |
selected |
attributes of the selection, see |
debounce |
amount of time to wait before firing an event (in milliseconds).
The default of 0 means do not debounce at all.
Debouncing is mainly useful when |
... |
currently not supported. |
Carson Sievert
https://plotly-r.com/client-side-linking.html
# These examples are designed to show you how to highlight/brush a *single* # view. For examples of multiple linked views, see `demo(package = "plotly")` d <- highlight_key(txhousing, ~city) p <- ggplot(d, aes(date, median, group = city)) + geom_line() gg <- ggplotly(p, tooltip = "city") highlight(gg, dynamic = TRUE) # supply custom colors to the brush cols <- toRGB(RColorBrewer::brewer.pal(3, "Dark2"), 0.5) highlight(gg, on = "plotly_hover", color = cols, dynamic = TRUE) # Use attrs_selected() for complete control over the selection appearance # note any relevant colors you specify here should override the color argument s <- attrs_selected( showlegend = TRUE, mode = "lines+markers", marker = list(symbol = "x") ) highlight(layout(gg, showlegend = TRUE), selected = s)
# These examples are designed to show you how to highlight/brush a *single* # view. For examples of multiple linked views, see `demo(package = "plotly")` d <- highlight_key(txhousing, ~city) p <- ggplot(d, aes(date, median, group = city)) + geom_line() gg <- ggplotly(p, tooltip = "city") highlight(gg, dynamic = TRUE) # supply custom colors to the brush cols <- toRGB(RColorBrewer::brewer.pal(3, "Dark2"), 0.5) highlight(gg, on = "plotly_hover", color = cols, dynamic = TRUE) # Use attrs_selected() for complete control over the selection appearance # note any relevant colors you specify here should override the color argument s <- attrs_selected( showlegend = TRUE, mode = "lines+markers", marker = list(symbol = "x") ) highlight(layout(gg, showlegend = TRUE), selected = s)
This function simply creates an object of class crosstalk::SharedData. The reason it exists is to make it easier to teach others how to leverage its functionality in plotly. It also makes it more discoverable if one is already aware of highlight.
highlight_key(x, ...)
highlight_key(x, ...)
x |
a plotly visualization or a |
... |
arguments passed to |
An object of class crosstalk::SharedData
Carson Sievert
Description TBD.
hobbs
hobbs
A data frame with three variables: r
, t
,
nms
.
Embed a plotly grid as an iframe in a knitr doc
knit_print.api_grid(x, options, ...)
knit_print.api_grid(x, options, ...)
x |
a plotly figure object |
options |
knitr options. |
... |
placeholder. |
https://github.com/yihui/knitr/blob/master/vignettes/knit_print.Rmd
Embed a plotly grid as an iframe in a knitr doc
knit_print.api_grid_local(x, options, ...)
knit_print.api_grid_local(x, options, ...)
x |
a plotly figure object |
options |
knitr options. |
... |
placeholder. |
https://github.com/yihui/knitr/blob/master/vignettes/knit_print.Rmd
Embed a plotly figure as an iframe in a knitr doc
knit_print.api_plot(x, options, ...)
knit_print.api_plot(x, options, ...)
x |
a plotly figure object |
options |
knitr options. |
... |
placeholder. |
https://github.com/yihui/knitr/blob/master/vignettes/knit_print.Rmd
Retrieve the last plot to be modified or created.
last_plot()
last_plot()
Modify the layout of a plotly visualization
layout(p, ..., data = NULL)
layout(p, ..., data = NULL)
p |
A plotly object. |
... |
Arguments to the layout object. For documentation, see https://plotly.com/r/reference/#Layout_and_layout_style_objects |
data |
A data frame to associate with this layout (optional). If not
provided, arguments are evaluated using the data frame in |
Carson Sievert
Description TBD.
mic
mic
A data frame with three variables: r
, t
,
nms
.
Deprecated in version 2.0 (offline plots are now the default)
offline(p, height, width, out_dir, open_browser)
offline(p, height, width, out_dir, open_browser)
p |
a plotly object |
height |
A valid CSS unit. (like "100\ which will be coerced to a string and have "px" appended. |
width |
A valid CSS unit. (like "100\ which will be coerced to a string and have "px" appended. |
out_dir |
a directory to place the visualization.
If |
open_browser |
open the visualization after creating it? |
a plotly object of class "offline"
Carson Sievert
This function is deprecated, use save_image()
instead.
orca( p, file = "plot.png", format = tools::file_ext(file), scale = NULL, width = NULL, height = NULL, mathjax = FALSE, parallel_limit = NULL, verbose = FALSE, debug = FALSE, safe = FALSE, more_args = NULL, ... ) orca_serve( port = 5151, mathjax = FALSE, safe = FALSE, request_limit = NULL, keep_alive = TRUE, window_max_number = NULL, quiet = FALSE, debug = FALSE, more_args = NULL, ... )
orca( p, file = "plot.png", format = tools::file_ext(file), scale = NULL, width = NULL, height = NULL, mathjax = FALSE, parallel_limit = NULL, verbose = FALSE, debug = FALSE, safe = FALSE, more_args = NULL, ... ) orca_serve( port = 5151, mathjax = FALSE, safe = FALSE, request_limit = NULL, keep_alive = TRUE, window_max_number = NULL, quiet = FALSE, debug = FALSE, more_args = NULL, ... )
p |
a plotly object. |
file |
output filename. |
format |
the output format (png, jpeg, webp, svg, pdf, eps). |
scale |
Sets the image scale. Applies to all output images. |
width |
Sets the image width. If not set, defaults to |
height |
Sets the image height. If not set, defaults to |
mathjax |
whether or not to include MathJax (required to render TeX).
If |
parallel_limit |
Sets the limit of parallel tasks run. |
verbose |
Turn on verbose logging on stdout. |
debug |
Starts app in debug mode and turn on verbose logs on stdout. |
safe |
Turns on safe mode: where figures likely to make browser window hang during image generating are skipped. |
more_args |
additional arguments to pass along to system command. This is useful
for specifying display and/or electron options, such as |
... |
for |
port |
Sets the server's port number. |
request_limit |
Sets a request limit that makes orca exit when reached. |
keep_alive |
Turn on keep alive mode where orca will (try to) relaunch server if process unexpectedly exits. |
window_max_number |
Sets maximum number of browser windows the server can keep open at a given time. |
quiet |
Suppress all logging info. |
The orca_serve()
function returns an object with two methods:
export(p, file = "plot.png", format = tools::file_ext(file), scale = NULL, width = NULL, height = NULL)
Export a static image of a plotly graph. Arguments found here are the same as those found in orca()
close()
Close down the orca server and kill the underlying node process.
The orca_serve()
function returns an object with two fields:
port
The port number that the server is listening to.
process
An R6 class for controlling and querying the underlying node process.
Carson Sievert
## Not run: # NOTE: in a headless environment, you may need to set `more_args="--enable-webgl"` # to export webgl correctly p <- plot_ly(z = ~volcano) %>% add_surface() orca(p, "surface-plot.svg") #' # launch the server server <- orca_serve() # export as many graphs as you'd like server$export(qplot(1:10), "test1.pdf") server$export(plot_ly(x = 1:10, y = 1:10), "test2.pdf") # the underlying process is exposed as a field, so you # have full control over the external process server$process$is_alive() # convenience method for closing down the server server$close() # remove the exported files from disk unlink("test1.pdf") unlink("test2.pdf") ## End(Not run)
## Not run: # NOTE: in a headless environment, you may need to set `more_args="--enable-webgl"` # to export webgl correctly p <- plot_ly(z = ~volcano) %>% add_surface() orca(p, "surface-plot.svg") #' # launch the server server <- orca_serve() # export as many graphs as you'd like server$export(qplot(1:10), "test1.pdf") server$export(plot_ly(x = 1:10, y = 1:10), "test2.pdf") # the underlying process is exposed as a field, so you # have full control over the external process server$process$is_alive() # convenience method for closing down the server server$close() # remove the exported files from disk unlink("test1.pdf") unlink("test2.pdf") ## End(Not run)
Leveraging plotly.js' partial bundles can lead to smaller file sizes and faster rendering. The full list of available bundles, and the trace types that they support, are available here
partial_bundle(p, type = "auto", local = TRUE, minified = TRUE)
partial_bundle(p, type = "auto", local = TRUE, minified = TRUE)
p |
a plotly object. |
type |
name of the (partial) bundle. The default, |
local |
whether or not to download the partial bundle so that it can be viewed later without an internet connection. |
minified |
whether or not to use a minified js file (non-minified file can be useful for debugging plotly.js) |
WARNING: use this function with caution when rendering multiple plotly graphs on a single website. That's because, if multiple plotly.js bundles are used, the most recent bundle will override the other bundles. See the examples section for an example.
Carson Sievert
# ---------------------------------------------------------------------- # This function is always safe to use when rendering a single # plotly graph. In this case, we get a 3x file reduction. # ---------------------------------------------------------------------- ## Not run: library(plotly) p <- plot_ly(x = 1:10, y = 1:10) %>% add_markers() save_widget <- function(p, f) { owd <- setwd(dirname(f)) on.exit(setwd(owd)) htmlwidgets::saveWidget(p, f) mb <- round(file.info(f)$size / 1e6, 3) message("File is: ", mb," MB") } f1 <- tempfile(fileext = ".html") f2 <- tempfile(fileext = ".html") save_widget(p, f1) save_widget(partial_bundle(p), f2) # ---------------------------------------------------------------------- # But, since plotly.js bundles override one another, # be careful when putting multiple graphs in a larger document! # Note how the surface (part of the gl3d bundle) renders, but the # heatmap (part of the cartesian bundle) doesn't... # ---------------------------------------------------------------------- library(htmltools) p1 <- plot_ly(z = ~volcano) %>% add_heatmap() %>% partial_bundle() p2 <- plot_ly(z = ~volcano) %>% add_surface() %>% partial_bundle() browsable(tagList(p1, p2)) ## End(Not run)
# ---------------------------------------------------------------------- # This function is always safe to use when rendering a single # plotly graph. In this case, we get a 3x file reduction. # ---------------------------------------------------------------------- ## Not run: library(plotly) p <- plot_ly(x = 1:10, y = 1:10) %>% add_markers() save_widget <- function(p, f) { owd <- setwd(dirname(f)) on.exit(setwd(owd)) htmlwidgets::saveWidget(p, f) mb <- round(file.info(f)$size / 1e6, 3) message("File is: ", mb," MB") } f1 <- tempfile(fileext = ".html") f2 <- tempfile(fileext = ".html") save_widget(p, f1) save_widget(partial_bundle(p), f2) # ---------------------------------------------------------------------- # But, since plotly.js bundles override one another, # be careful when putting multiple graphs in a larger document! # Note how the surface (part of the gl3d bundle) renders, but the # heatmap (part of the cartesian bundle) doesn't... # ---------------------------------------------------------------------- library(htmltools) p1 <- plot_ly(z = ~volcano) %>% add_heatmap() %>% partial_bundle() p2 <- plot_ly(z = ~volcano) %>% add_surface() %>% partial_bundle() browsable(tagList(p1, p2)) ## End(Not run)
This function takes advantage of nested key selections to implement an interactive dendrogram. Selecting a node selects all the labels (i.e. leafs) under that node.
plot_dendro(d, set = "A", xmin = -50, height = 500, width = 500, ...)
plot_dendro(d, set = "A", xmin = -50, height = 500, width = 500, ...)
d |
a dendrogram object |
set |
defines a crosstalk group |
xmin |
minimum of the range of the x-scale |
height |
height |
width |
width |
... |
arguments supplied to |
Carson Sievert
plot_ly()
, plot_mapbox()
, ggplotly()
## Not run: hc <- hclust(dist(USArrests), "ave") dend1 <- as.dendrogram(hc) plot_dendro(dend1, height = 600) %>% hide_legend() %>% highlight(persistent = TRUE, dynamic = TRUE) ## End(Not run)
## Not run: hc <- hclust(dist(USArrests), "ave") dend1 <- as.dendrogram(hc) plot_dendro(dend1, height = 600) %>% hide_legend() %>% highlight(persistent = TRUE, dynamic = TRUE) ## End(Not run)
Use this function instead of plot_ly()
to initialize
a plotly-geo object. This enforces the entire plot so use
the scattergeo trace type, and enables higher level geometries
like add_polygons()
to work
plot_geo(data = data.frame(), ..., offline = FALSE)
plot_geo(data = data.frame(), ..., offline = FALSE)
data |
A data frame (optional). |
... |
arguments passed along to |
offline |
whether or not to include geo assets so that the map can be viewed with or without an internet connection. The plotlyGeoAssets package is required for this functionality. |
Carson Sievert
plot_ly()
, plot_mapbox()
, ggplotly()
map_data("world", "canada") %>% group_by(group) %>% plot_geo(x = ~long, y = ~lat) %>% add_markers(size = I(1))
map_data("world", "canada") %>% group_by(group) %>% plot_geo(x = ~long, y = ~lat) %>% add_markers(size = I(1))
This function maps R objects to plotly.js,
an (MIT licensed) web-based interactive charting library. It provides
abstractions for doing common things (e.g. mapping data values to
fill colors (via color
) or creating animations (via frame
)) and sets
some different defaults to make the interface feel more 'R-like'
(i.e., closer to plot()
and ggplot2::qplot()
).
plot_ly( data = data.frame(), ..., type = NULL, name, color, colors = NULL, alpha = NULL, stroke, strokes = NULL, alpha_stroke = 1, size, sizes = c(10, 100), span, spans = c(1, 20), symbol, symbols = NULL, linetype, linetypes = NULL, split, frame, width = NULL, height = NULL, source = "A" )
plot_ly( data = data.frame(), ..., type = NULL, name, color, colors = NULL, alpha = NULL, stroke, strokes = NULL, alpha_stroke = 1, size, sizes = c(10, 100), span, spans = c(1, 20), symbol, symbols = NULL, linetype, linetypes = NULL, split, frame, width = NULL, height = NULL, source = "A" )
data |
A data frame (optional) or crosstalk::SharedData object. |
... |
Arguments (i.e., attributes) passed along to the trace |
type |
A character string specifying the trace type (e.g. |
name |
Values mapped to the trace's name attribute. Since a trace can
only have one name, this argument acts very much like |
color |
Values mapped to relevant 'fill-color' attribute(s)
(e.g. fillcolor,
marker.color,
textfont.color, etc.).
The mapping from data values to color codes may be controlled using
|
colors |
Either a colorbrewer2.org palette name (e.g. "YlOrRd" or "Blues"),
or a vector of colors to interpolate in hexadecimal "#RRGGBB" format,
or a color interpolation function like |
alpha |
A number between 0 and 1 specifying the alpha channel applied to |
stroke |
Similar to |
strokes |
Similar to |
alpha_stroke |
Similar to |
size |
(Numeric) values mapped to relevant 'fill-size' attribute(s)
(e.g., marker.size,
textfont.size,
and error_x.width).
The mapping from data values to symbols may be controlled using
|
sizes |
A numeric vector of length 2 used to scale |
span |
(Numeric) values mapped to relevant 'stroke-size' attribute(s)
(e.g.,
marker.line.width,
line.width for filled polygons,
and error_x.thickness)
The mapping from data values to symbols may be controlled using
|
spans |
A numeric vector of length 2 used to scale |
symbol |
(Discrete) values mapped to marker.symbol.
The mapping from data values to symbols may be controlled using
|
symbols |
A character vector of pch values or symbol names. |
linetype |
(Discrete) values mapped to line.dash.
The mapping from data values to symbols may be controlled using
|
linetypes |
A character vector of |
split |
(Discrete) values used to create multiple traces (one trace per value). |
frame |
(Discrete) values used to create animation frames. |
width |
Width in pixels (optional, defaults to automatic sizing). |
height |
Height in pixels (optional, defaults to automatic sizing). |
source |
a character string of length 1. Match the value of this string
with the source argument in |
Unless type
is specified, this function just initiates a plotly
object with 'global' attributes that are passed onto downstream uses of
add_trace()
(or similar). A formula must always be used when
referencing column name(s) in data
(e.g. plot_ly(mtcars, x = ~wt)
).
Formulas are optional when supplying values directly, but they do
help inform default axis/scale titles
(e.g., plot_ly(x = mtcars$wt)
vs plot_ly(x = ~mtcars$wt)
)
Carson Sievert
https://plotly-r.com/overview.html
For initializing a plotly-geo object: plot_geo()
For initializing a plotly-mapbox object: plot_mapbox()
For translating a ggplot2 object to a plotly object: ggplotly()
For modifying any plotly object: layout()
, add_trace()
, style()
For linked brushing: highlight()
For arranging multiple plots: subplot()
, crosstalk::bscols()
For inspecting plotly objects: plotly_json()
For quick, accurate, and searchable plotly.js reference: schema()
## Not run: # plot_ly() tries to create a sensible plot based on the information you # give it. If you don't provide a trace type, plot_ly() will infer one. plot_ly(economics, x = ~pop) plot_ly(economics, x = ~date, y = ~pop) # plot_ly() doesn't require data frame(s), which allows one to take # advantage of trace type(s) designed specifically for numeric matrices plot_ly(z = ~volcano) plot_ly(z = ~volcano, type = "surface") # plotly has a functional interface: every plotly function takes a plotly # object as it's first input argument and returns a modified plotly object add_lines(plot_ly(economics, x = ~date, y = ~unemploy/pop)) # To make code more readable, plotly imports the pipe operator from magrittr economics %>% plot_ly(x = ~date, y = ~unemploy/pop) %>% add_lines() # Attributes defined via plot_ly() set 'global' attributes that # are carried onto subsequent traces, but those may be over-written plot_ly(economics, x = ~date, color = I("black")) %>% add_lines(y = ~uempmed) %>% add_lines(y = ~psavert, color = I("red")) # Attributes are documented in the figure reference -> https://plotly.com/r/reference # You might notice plot_ly() has named arguments that aren't in this figure # reference. These arguments make it easier to map abstract data values to # visual attributes. p <- plot_ly(palmerpenguins::penguins, x = ~bill_length_mm, y = ~body_mass_g) add_markers(p, color = ~bill_depth_mm, size = ~bill_depth_mm) add_markers(p, color = ~species) add_markers(p, color = ~species, colors = "Set1") add_markers(p, symbol = ~species) add_paths(p, linetype = ~species) ## End(Not run)
## Not run: # plot_ly() tries to create a sensible plot based on the information you # give it. If you don't provide a trace type, plot_ly() will infer one. plot_ly(economics, x = ~pop) plot_ly(economics, x = ~date, y = ~pop) # plot_ly() doesn't require data frame(s), which allows one to take # advantage of trace type(s) designed specifically for numeric matrices plot_ly(z = ~volcano) plot_ly(z = ~volcano, type = "surface") # plotly has a functional interface: every plotly function takes a plotly # object as it's first input argument and returns a modified plotly object add_lines(plot_ly(economics, x = ~date, y = ~unemploy/pop)) # To make code more readable, plotly imports the pipe operator from magrittr economics %>% plot_ly(x = ~date, y = ~unemploy/pop) %>% add_lines() # Attributes defined via plot_ly() set 'global' attributes that # are carried onto subsequent traces, but those may be over-written plot_ly(economics, x = ~date, color = I("black")) %>% add_lines(y = ~uempmed) %>% add_lines(y = ~psavert, color = I("red")) # Attributes are documented in the figure reference -> https://plotly.com/r/reference # You might notice plot_ly() has named arguments that aren't in this figure # reference. These arguments make it easier to map abstract data values to # visual attributes. p <- plot_ly(palmerpenguins::penguins, x = ~bill_length_mm, y = ~body_mass_g) add_markers(p, color = ~bill_depth_mm, size = ~bill_depth_mm) add_markers(p, color = ~species) add_markers(p, color = ~species, colors = "Set1") add_markers(p, symbol = ~species) add_paths(p, linetype = ~species) ## End(Not run)
Use this function instead of plot_ly()
to initialize
a plotly-mapbox object. This enforces the entire plot so use
the scattermapbox trace type, and enables higher level geometries
like add_polygons()
to work
plot_mapbox(data = data.frame(), ...)
plot_mapbox(data = data.frame(), ...)
data |
A data frame (optional). |
... |
arguments passed along to |
Carson Sievert
plot_ly()
, plot_geo()
, ggplotly()
## Not run: plot_mapbox(res_mn) plot_mapbox(res_mn, color = ~INDRESNAME) map_data("world", "canada") %>% group_by(group) %>% plot_mapbox(x = ~long, y = ~lat) %>% add_polygons() %>% layout( mapbox = list( center = list(lat = ~median(lat), lon = ~median(long)) ) ) ## End(Not run)
## Not run: plot_mapbox(res_mn) plot_mapbox(res_mn, color = ~INDRESNAME) map_data("world", "canada") %>% group_by(group) %>% plot_mapbox(x = ~long, y = ~lat) %>% add_polygons() %>% layout( mapbox = list( center = list(lat = ~median(lat), lon = ~median(long)) ) ) ## End(Not run)
This generic function creates the list object sent to plotly.js
for rendering. Using this function can be useful for overriding defaults
provided by ggplotly
/plot_ly
or for debugging rendering
errors.
plotly_build(p, registerFrames = TRUE)
plotly_build(p, registerFrames = TRUE)
p |
a ggplot object, or a plotly object, or a list. |
registerFrames |
should a frame trace attribute be interpreted as frames in an animation? |
p <- plot_ly(economics, x = ~date, y = ~pce) # the unevaluated plotly object str(p) # the evaluated data str(plotly_build(p)$x$data)
p <- plot_ly(economics, x = ~date, y = ~pce) # the unevaluated plotly object str(p) # the evaluated data str(plotly_build(p)$x$data)
plotly_data()
returns data associated with
a plotly visualization (if there are multiple data frames, by default,
it returns the most recent one).
plotly_data(p, id = p$x$cur_data) ## S3 method for class 'plotly' groups(x) ## S3 method for class 'plotly' ungroup(x, ...) ## S3 method for class 'plotly' group_by(.data, ...) ## S3 method for class 'plotly' mutate(.data, ...) ## S3 method for class 'plotly' do(.data, ...) ## S3 method for class 'plotly' summarise(.data, ...) ## S3 method for class 'plotly' arrange(.data, ...) ## S3 method for class 'plotly' select(.data, ...) ## S3 method for class 'plotly' filter(.data, ...) ## S3 method for class 'plotly' distinct(.data, ...) ## S3 method for class 'plotly' slice(.data, ...) ## S3 method for class 'plotly' rename(.data, ...) ## S3 method for class 'plotly' transmute(.data, ...) ## S3 method for class 'plotly' group_by_(.data, ...) ## S3 method for class 'plotly' mutate_(.data, ...) ## S3 method for class 'plotly' do_(.data, ...) ## S3 method for class 'plotly' summarise_(.data, ...) ## S3 method for class 'plotly' arrange_(.data, ...) ## S3 method for class 'plotly' select_(.data, ...) ## S3 method for class 'plotly' filter_(.data, ...) ## S3 method for class 'plotly' distinct_(.data, ...) ## S3 method for class 'plotly' slice_(.data, ...) ## S3 method for class 'plotly' rename_(.data, ...) ## S3 method for class 'plotly' transmute_(.data, ...)
plotly_data(p, id = p$x$cur_data) ## S3 method for class 'plotly' groups(x) ## S3 method for class 'plotly' ungroup(x, ...) ## S3 method for class 'plotly' group_by(.data, ...) ## S3 method for class 'plotly' mutate(.data, ...) ## S3 method for class 'plotly' do(.data, ...) ## S3 method for class 'plotly' summarise(.data, ...) ## S3 method for class 'plotly' arrange(.data, ...) ## S3 method for class 'plotly' select(.data, ...) ## S3 method for class 'plotly' filter(.data, ...) ## S3 method for class 'plotly' distinct(.data, ...) ## S3 method for class 'plotly' slice(.data, ...) ## S3 method for class 'plotly' rename(.data, ...) ## S3 method for class 'plotly' transmute(.data, ...) ## S3 method for class 'plotly' group_by_(.data, ...) ## S3 method for class 'plotly' mutate_(.data, ...) ## S3 method for class 'plotly' do_(.data, ...) ## S3 method for class 'plotly' summarise_(.data, ...) ## S3 method for class 'plotly' arrange_(.data, ...) ## S3 method for class 'plotly' select_(.data, ...) ## S3 method for class 'plotly' filter_(.data, ...) ## S3 method for class 'plotly' distinct_(.data, ...) ## S3 method for class 'plotly' slice_(.data, ...) ## S3 method for class 'plotly' rename_(.data, ...) ## S3 method for class 'plotly' transmute_(.data, ...)
p |
a plotly visualization. |
id |
a character string or number referencing an "attribute layer". |
x |
a plotly visualization. |
... |
arguments passed onto the relevant method. |
.data |
a plotly visualization. |
# use group_by() to define groups of visual markings p <- txhousing %>% group_by(city) %>% plot_ly(x = ~date, y = ~sales) p # plotly objects preserve data groupings groups(p) plotly_data(p) # dplyr verbs operate on plotly objects as if they were data frames p <- economics %>% plot_ly(x = ~date, y = ~unemploy / pop) %>% add_lines() %>% mutate(rate = unemploy / pop) %>% filter(rate == max(rate)) plotly_data(p) add_markers(p) layout(p, annotations = list(x = ~date, y = ~rate, text = "peak")) # use group_by() + do() + subplot() for trellis displays d <- group_by(mpg, drv) plots <- do(d, p = plot_ly(., x = ~cty, name = ~drv)) subplot(plots[["p"]], nrows = 3, shareX = TRUE) # arrange displays by their mean means <- summarise(d, mn = mean(cty, na.rm = TRUE)) means %>% dplyr::left_join(plots) %>% arrange(mn) %>% subplot(nrows = NROW(.), shareX = TRUE) # more dplyr verbs applied to plotly objects p <- mtcars %>% plot_ly(x = ~wt, y = ~mpg, name = "scatter trace") %>% add_markers() p %>% slice(1) %>% plotly_data() p %>% slice(1) %>% add_markers(name = "first observation") p %>% filter(cyl == 4) %>% plotly_data() p %>% filter(cyl == 4) %>% add_markers(name = "four cylinders")
# use group_by() to define groups of visual markings p <- txhousing %>% group_by(city) %>% plot_ly(x = ~date, y = ~sales) p # plotly objects preserve data groupings groups(p) plotly_data(p) # dplyr verbs operate on plotly objects as if they were data frames p <- economics %>% plot_ly(x = ~date, y = ~unemploy / pop) %>% add_lines() %>% mutate(rate = unemploy / pop) %>% filter(rate == max(rate)) plotly_data(p) add_markers(p) layout(p, annotations = list(x = ~date, y = ~rate, text = "peak")) # use group_by() + do() + subplot() for trellis displays d <- group_by(mpg, drv) plots <- do(d, p = plot_ly(., x = ~cty, name = ~drv)) subplot(plots[["p"]], nrows = 3, shareX = TRUE) # arrange displays by their mean means <- summarise(d, mn = mean(cty, na.rm = TRUE)) means %>% dplyr::left_join(plots) %>% arrange(mn) %>% subplot(nrows = NROW(.), shareX = TRUE) # more dplyr verbs applied to plotly objects p <- mtcars %>% plot_ly(x = ~wt, y = ~mpg, name = "scatter trace") %>% add_markers() p %>% slice(1) %>% plotly_data() p %>% slice(1) %>% add_markers(name = "first observation") p %>% filter(cyl == 4) %>% plotly_data() p %>% filter(cyl == 4) %>% add_markers(name = "four cylinders")
Useful when used with subplot()
plotly_empty(...)
plotly_empty(...)
... |
arguments passed onto |
Provides a unified interface for running demos, shiny apps, and Rmd documents which are bundled with the package.
plotly_example(type = c("demo", "shiny", "rmd"), name, edit = TRUE, ...)
plotly_example(type = c("demo", "shiny", "rmd"), name, edit = TRUE, ...)
type |
the type of example |
name |
the name of the example (valid names depend on |
edit |
whether to open the relevant source files using file.edit. Only relevant if |
... |
arguments passed onto the suitable method. |
Carson Sievert
The images endpoint turns a plot (which may be given in multiple forms) into an image of the desired format.
plotly_IMAGE( x, width = 1000, height = 500, format = "png", scale = 1, out_file, ... )
plotly_IMAGE( x, width = 1000, height = 500, format = "png", scale = 1, out_file, ... )
x |
either a plotly object or a list. |
width |
Image width in pixels |
height |
Image height in pixels |
format |
The desired image format 'png', 'jpeg', 'svg', 'pdf', 'eps', or 'webp' |
scale |
Both png and jpeg formats will be scaled beyond the specified width and height by this number. |
out_file |
A filename for writing the image to a file. |
... |
arguments passed onto |
## Not run: p <- plot_ly(x = 1:10) Png <- plotly_IMAGE(p, out_file = "plotly-test-image.png") Jpeg <- plotly_IMAGE(p, format = "jpeg", out_file = "plotly-test-image.jpeg") Svg <- plotly_IMAGE(p, format = "svg", out_file = "plotly-test-image.svg") Pdf <- plotly_IMAGE(p, format = "pdf", out_file = "plotly-test-image.pdf") ## End(Not run)
## Not run: p <- plot_ly(x = 1:10) Png <- plotly_IMAGE(p, out_file = "plotly-test-image.png") Jpeg <- plotly_IMAGE(p, format = "jpeg", out_file = "plotly-test-image.jpeg") Svg <- plotly_IMAGE(p, format = "svg", out_file = "plotly-test-image.svg") Pdf <- plotly_IMAGE(p, format = "pdf", out_file = "plotly-test-image.pdf") ## End(Not run)
This function is useful for obtaining/viewing/debugging JSON sent to plotly.js.
plotly_json(p = last_plot(), jsonedit = interactive(), pretty = TRUE, ...)
plotly_json(p = last_plot(), jsonedit = interactive(), pretty = TRUE, ...)
p |
a plotly or ggplot object. |
jsonedit |
use listviewer::jsonedit to view the JSON? |
pretty |
adds indentation whitespace to JSON output. Can be TRUE/FALSE or a number specifying the number of spaces to indent. See jsonlite::prettify. |
... |
other options passed onto listviewer::jsonedit |
plotly_json(plot_ly()) plotly_json(plot_ly(), FALSE)
plotly_json(plot_ly()) plotly_json(plot_ly(), FALSE)
Deprecated: see api_create()
.
plotly_POST( x = last_plot(), filename = NULL, fileopt = "overwrite", sharing = c("public", "private", "secret"), ... )
plotly_POST( x = last_plot(), filename = NULL, fileopt = "overwrite", sharing = c("public", "private", "secret"), ... )
x |
either a ggplot object, a plotly object, or a list. |
filename |
character string describing the name of the plot in your plotly account. Use / to specify directories. If a directory path does not exist it will be created. If this argument is not specified and the title of the plot exists, that will be used for the filename. |
fileopt |
character string describing whether to create a "new" plotly, "overwrite" an existing plotly, "append" data to existing plotly, or "extend" it. |
sharing |
If 'public', anyone can view this graph. It will appear in your profile and can appear in search engines. You do not need to be logged in to Plotly to view this chart. If 'private', only you can view this plot. It will not appear in the Plotly feed, your profile, or search engines. You must be logged in to Plotly to view this graph. You can privately share this graph with other Plotly users in your online Plotly account and they will need to be logged in to view this plot. If 'secret', anyone with this secret link can view this chart. It will not appear in the Plotly feed, your profile, or search engines. If it is embedded inside a webpage or an IPython notebook, anybody who is viewing that page will be able to view the graph. You do not need to be logged in to view this plot. |
... |
not used |
Output and render functions for using plotly within Shiny applications and interactive Rmd documents.
plotlyOutput( outputId, width = "100%", height = "400px", inline = FALSE, reportTheme = TRUE, fill = !inline ) renderPlotly(expr, env = parent.frame(), quoted = FALSE)
plotlyOutput( outputId, width = "100%", height = "400px", inline = FALSE, reportTheme = TRUE, fill = !inline ) renderPlotly(expr, env = parent.frame(), quoted = FALSE)
outputId |
output variable to read from |
width , height
|
Must be a valid CSS unit (like |
inline |
use an inline ( |
reportTheme |
whether or not to report CSS styles (if a sufficient version of shiny and htmlwidgets is available). |
fill |
see |
expr |
An expression that generates a plotly |
env |
The environment in which to evaluate |
quoted |
Is |
Modify a plotly object inside a shiny app
plotlyProxy( outputId, session = shiny::getDefaultReactiveDomain(), deferUntilFlush = TRUE ) plotlyProxyInvoke(p, method, ...)
plotlyProxy( outputId, session = shiny::getDefaultReactiveDomain(), deferUntilFlush = TRUE ) plotlyProxyInvoke(p, method, ...)
outputId |
single-element character vector indicating the output ID map to modify (if invoked from a Shiny module, the namespace will be added automatically) |
session |
the Shiny session object to which the map belongs; usually the default value will suffice. |
deferUntilFlush |
indicates whether actions performed against this instance should be carried out right away, or whether they should be held until after the next time all of the outputs are updated. |
p |
a plotly proxy object (created with |
method |
a plotlyjs method to invoke. For a list of options, visit https://plotly.com/javascript/plotlyjs-function-reference/ |
... |
unnamed arguments passed onto the plotly.js method |
if (require("shiny") && interactive()) { plotly_example("shiny", "proxy_relayout") plotly_example("shiny", "proxy_mapbox") }
if (require("shiny") && interactive()) { plotly_example("shiny", "proxy_relayout") plotly_example("shiny", "proxy_mapbox") }
Print method for a 'generic' API response
## S3 method for class 'api' print(x, ...)
## S3 method for class 'api' print(x, ...)
x |
a list. |
... |
additional arguments (currently ignored) |
Print a plotly grid object
## S3 method for class 'api_grid' print(x, ...)
## S3 method for class 'api_grid' print(x, ...)
x |
a plotly grid object |
... |
additional arguments (currently ignored) |
Print a plotly grid object
## S3 method for class 'api_grid_local' print(x, ...)
## S3 method for class 'api_grid_local' print(x, ...)
x |
a plotly grid object |
... |
additional arguments (currently ignored) |
Print a plot on plotly's platform
## S3 method for class 'api_plot' print(x, ...)
## S3 method for class 'api_plot' print(x, ...)
x |
a plotly figure object |
... |
additional arguments (currently ignored) |
Add a range slider to the x-axis
rangeslider(p, start = NULL, end = NULL, ...)
rangeslider(p, start = NULL, end = NULL, ...)
p |
plotly object. |
start |
a start date/value. |
end |
an end date/value. |
... |
these arguments are documented here https://plotly.com/r/reference/#layout-xaxis-rangeslider |
Carson Sievert
plot_ly(x = time(USAccDeaths), y = USAccDeaths) %>% add_lines() %>% rangeslider() d <- tibble::tibble( time = seq(as.Date("2016-01-01"), as.Date("2016-08-31"), by = "days"), y = rnorm(seq_along(time)) ) plot_ly(d, x = ~time, y = ~y) %>% add_lines() %>% rangeslider(d$time[5], d$time[50])
plot_ly(x = time(USAccDeaths), y = USAccDeaths) %>% add_lines() %>% rangeslider() d <- tibble::tibble( time = seq(as.Date("2016-01-01"), as.Date("2016-08-31"), by = "days"), y = rnorm(seq_along(time)) ) plot_ly(d, x = ~time, y = ~y) %>% add_lines() %>% rangeslider(d$time[5], d$time[50])
Encode a raster object as a data URI, which is suitable for
use with layout()
images.
This is especially convenient for embedding raster images on a plot in
a self-contained fashion (i.e., so they don't depend on external URL links).
raster2uri(r, ...)
raster2uri(r, ...)
r |
an object coercable to a raster object via |
... |
arguments passed onto |
Carson Sievert
https://plotly-r.com/embedding-images.html
# a red gradient (from ?as.raster) r <- as.raster(matrix(hcl(0, 80, seq(50, 80, 10)), nrow = 4, ncol = 5)) plot(r) # embed the raster as an image plot_ly(x = 1, y = 1) %>% layout( images = list(list( source = raster2uri(r), xref = "paper", yref = "paper", x = 0, y = 0, sizex = 0.5, sizey = 0.5, xanchor = "left", yanchor = "bottom" )) )
# a red gradient (from ?as.raster) r <- as.raster(matrix(hcl(0, 80, seq(50, 80, 10)), nrow = 4, ncol = 5)) plot(r) # embed the raster as an image plot_ly(x = 1, y = 1) %>% layout( images = list(list( source = raster2uri(r), xref = "paper", yref = "paper", x = 0, y = 0, sizex = 0.5, sizey = 0.5, xanchor = "left", yanchor = "bottom" )) )
By default, plotly.js' TypedArray polyfill is included as a dependency, so printing "just works" in any context. Many users won't need this polyfill, so this function may be used to remove it and thus reduce the size of the page.
remove_typedarray_polyfill(p)
remove_typedarray_polyfill(p)
p |
a plotly object |
The polyfill seems to be only relevant for those rendering plots via phantomjs and RStudio on some Windows platforms.
## Not run: p1 <- plot_ly() p2 <- remove_typedarray_polyfill(p1) t1 <- tempfile(fileext = ".html") htmlwidgets::saveWidget(p1, t1) file.info(t1)$size htmlwidgets::saveWidget(p2, t1) file.info(t1)$size ## End(Not run)
## Not run: p1 <- plot_ly() p2 <- remove_typedarray_polyfill(p1) t1 <- tempfile(fileext = ".html") htmlwidgets::saveWidget(p1, t1) file.info(t1)$size htmlwidgets::saveWidget(p2, t1) file.info(t1)$size ## End(Not run)
Minnesotan Indian Reservation Lands
res_mn
res_mn
An sf data frame with 13 features and 5 fields
https://www.dot.state.mn.us/maps/gdma/gis-data.html
Static image exporting via the kaleido python package. kaleido()
imports
kaleido into a reticulated Python session and returns a $transform()
method for converting R plots into static images. save_image()
provides a convenience wrapper around kaleido()$transform()
.
save_image(p, file, ..., width = NULL, height = NULL, scale = NULL) kaleido(...)
save_image(p, file, ..., width = NULL, height = NULL, scale = NULL) kaleido(...)
p |
a plot object. |
file |
a file path with a suitable file extension (png, jpg, jpeg, webp, svg, or pdf). |
... |
not currently used. |
width , height
|
The width/height of the exported image in layout
pixels. If |
scale |
The scale factor to use when exporting the figure. A scale factor larger than 1.0 will increase the image resolution with respect to the figure's layout pixel dimensions. Whereas as scale factor of less than 1.0 will decrease the image resolution. |
For save_image()
, the generated file
. For kaleido()
, an environment that contains:
transform()
: a function to convert plots objects into static images. This function has the same signature (i.e., arguments) as save_image()
shutdown()
: a function for shutting down any currently running subprocesses
that were launched via transform()
scope
: a reference to the underlying kaleido.scopes.plotly.PlotlyScope
python object. Modify this object to customize the underlying Chromium
subprocess and/or configure other details such as URL to plotly.js, MathJax, etc.
kaleido()
requires the kaleido python package to be usable via the
reticulate package. If you're starting from scratch, you install
eveything you need with the following R code:
install.packages("reticulate") library(reticulate) use_python(install_python()) py_install(c("kaleido", "plotly"))
## Not run: # Save a single image p <- plot_ly(x = 1:10) tmp <- tempfile(fileext = ".png") save_image(p, tmp) file.show(tmp) # Efficiently save multiple images scope <- kaleido() for (i in 1:5) { scope$transform(p, tmp) } # Remove and garbage collect to remove # R/Python objects and shutdown subprocesses rm(scope); gc() ## End(Not run)
## Not run: # Save a single image p <- plot_ly(x = 1:10) tmp <- tempfile(fileext = ".png") save_image(p, tmp) file.show(tmp) # Efficiently save multiple images scope <- kaleido() for (i in 1:5) { scope$transform(p, tmp) } # Remove and garbage collect to remove # R/Python objects and shutdown subprocesses rm(scope); gc() ## End(Not run)
The schema contains valid attributes names, their value type, default values (if any), and min/max values (if applicable).
schema(jsonedit = interactive(), ...)
schema(jsonedit = interactive(), ...)
jsonedit |
use |
... |
other options passed onto |
s <- schema() # retrieve acceptable `layout.mapbox.style` values if (!is.na(Sys.getenv('MAPBOX_TOKEN', NA))) { styles <- s$layout$layoutAttributes$mapbox$style$values subplot( plot_mapbox() %>% layout(mapbox = list(style = styles[3])), plot_mapbox() %>% layout(mapbox = list(style = styles[5])) ) }
s <- schema() # retrieve acceptable `layout.mapbox.style` values if (!is.na(Sys.getenv('MAPBOX_TOKEN', NA))) { styles <- s$layout$layoutAttributes$mapbox$style$values subplot( plot_mapbox() %>% layout(mapbox = list(style = styles[3])), plot_mapbox() %>% layout(mapbox = list(style = styles[5])) ) }
Useful for viewing colors after they've been converted to plotly.js' color format – "rgba(255, 255, 255, 1)"
showRGB(x, ...)
showRGB(x, ...)
x |
character string specifying color(s). |
... |
arguments passed along to |
Carson Sievert
showRGB(toRGB(colors()), labels = FALSE)
showRGB(toRGB(colors()), labels = FALSE)
A sign up interface to plotly through the R Console.
signup(username, email, save = TRUE)
signup(username, email, save = TRUE)
username |
Desired username. |
email |
Desired email. |
save |
If request is successful, should the username & API key be automatically stored as an environment variable in a .Rprofile? |
api_key key to use with the api
tmp_pw temporary password to access your plotly account
https://plotly.com/rest/
## Not run: # You need a plotly username and API key to communicate with the plotly API. # If you don't already have an API key, you can obtain one with a valid # username and email via signup(). s <- signup('anna.lyst', '[email protected]') # If you already have a username and API key, please create the following # environment variables: Sys.setenv("plotly_username" = "me") Sys.setenv("plotly_api_key" = "mykey") # You can also change the default domain if you have a plotly server. Sys.setenv("plotly_domain" = "http://mydomain.com") # If you want to automatically load these environment variables when you # start R, you can put them inside your ~/.Rprofile # (see help(.Rprofile) for more details) ## End(Not run)
## Not run: # You need a plotly username and API key to communicate with the plotly API. # If you don't already have an API key, you can obtain one with a valid # username and email via signup(). s <- signup('anna.lyst', '[email protected]') # If you already have a username and API key, please create the following # environment variables: Sys.setenv("plotly_username" = "me") Sys.setenv("plotly_api_key" = "mykey") # You can also change the default domain if you have a plotly server. Sys.setenv("plotly_domain" = "http://mydomain.com") # If you want to automatically load these environment variables when you # start R, you can put them inside your ~/.Rprofile # (see help(.Rprofile) for more details) ## End(Not run)
Modify trace(s) of an existing plotly visualization. Useful when used in
conjunction with get_figure()
.
style(p, ..., traces = NULL)
style(p, ..., traces = NULL)
p |
A plotly visualization. |
... |
Visual properties. |
traces |
numeric vector. Which traces should be modified? By default,
attributes place in |
Carson Sievert
# style() is especially useful in conjunction with ggplotly() # It allows you to leverage the underlying plotly.js library to change # the return result of ggplotly() (p <- ggplotly(qplot(data = mtcars, wt, mpg, geom = c("point", "smooth")))) # removes hoverinfo for the line/ribbon traces (use `plotly_json()` to verify!) style(p, hoverinfo = "none", traces = c(2, 3)) # another example with plot_ly() instead of ggplotly() marker <- list( color = "red", line = list( width = 20, color = "black" ) ) (p <- plot_ly(x = 1:10, y = 1:10, marker = marker)) # note how the entire (marker) object is replaced if a list is provided style(p, marker = list(line = list(color = "blue"))) # similar to plotly.js, you can update a particular attribute like so # https://github.com/plotly/plotly.js/issues/1866#issuecomment-314115744 style(p, marker.line.color = "blue") # this clobbers the previously supplied marker.line.color style(p, marker.line = list(width = 2.5), marker.size = 10)
# style() is especially useful in conjunction with ggplotly() # It allows you to leverage the underlying plotly.js library to change # the return result of ggplotly() (p <- ggplotly(qplot(data = mtcars, wt, mpg, geom = c("point", "smooth")))) # removes hoverinfo for the line/ribbon traces (use `plotly_json()` to verify!) style(p, hoverinfo = "none", traces = c(2, 3)) # another example with plot_ly() instead of ggplotly() marker <- list( color = "red", line = list( width = 20, color = "black" ) ) (p <- plot_ly(x = 1:10, y = 1:10, marker = marker)) # note how the entire (marker) object is replaced if a list is provided style(p, marker = list(line = list(color = "blue"))) # similar to plotly.js, you can update a particular attribute like so # https://github.com/plotly/plotly.js/issues/1866#issuecomment-314115744 style(p, marker.line.color = "blue") # this clobbers the previously supplied marker.line.color style(p, marker.line = list(width = 2.5), marker.size = 10)
View multiple plots in a single view
subplot( ..., nrows = 1, widths = NULL, heights = NULL, margin = 0.02, shareX = FALSE, shareY = FALSE, titleX = shareX, titleY = shareY, which_layout = "merge" )
subplot( ..., nrows = 1, widths = NULL, heights = NULL, margin = 0.02, shareX = FALSE, shareY = FALSE, titleX = shareX, titleY = shareY, which_layout = "merge" )
... |
One of the following
|
nrows |
number of rows for laying out plots in a grid-like structure. Only used if no domain is already specified. |
widths |
relative width of each column on a 0-1 scale. By default all columns have an equal relative width. |
heights |
relative height of each row on a 0-1 scale. By default all rows have an equal relative height. |
margin |
either a single value or four values (all between 0 and 1). If four values are provided, the first is used as the left margin, the second is used as the right margin, the third is used as the top margin, and the fourth is used as the bottom margin. If a single value is provided, it will be used as all four margins. |
shareX |
should the x-axis be shared amongst the subplots? |
shareY |
should the y-axis be shared amongst the subplots? |
titleX |
should x-axis titles be retained? |
titleY |
should y-axis titles be retained? |
which_layout |
adopt the layout of which plot? If the default value of "merge" is used, layout options found later in the sequence of plots will override options found earlier in the sequence. This argument also accepts a numeric vector specifying which plots to consider when merging. |
A plotly object
Carson Sievert
# pass any number of plotly objects to subplot() p1 <- plot_ly(economics, x = ~date, y = ~uempmed) p2 <- plot_ly(economics, x = ~date, y = ~unemploy) subplot(p1, p2, p1, p2, nrows = 2, margin = 0.05) #' # anchor multiple traces on the same legend entry p1 <- add_lines(p1, color = I("black"), name = "1st", legendgroup = "1st") p2 <- add_lines(p2, color = I("red"), name = "2nd", legendgroup = "2nd") subplot( p1, style(p1, showlegend = FALSE), p2, style(p2, showlegend = FALSE), nrows = 2, margin = 0.05 ) # or pass a list economics_long %>% split(.$variable) %>% lapply(function(d) plot_ly(d, x = ~date, y = ~value)) %>% subplot(nrows = NROW(.), shareX = TRUE) # or pass a tibble with a list-column of plotly objects economics_long %>% group_by(variable) %>% do(p = plot_ly(., x = ~date, y = ~value)) %>% subplot(nrows = NROW(.), shareX = TRUE) # learn more at https://plotly.com/r/subplots/
# pass any number of plotly objects to subplot() p1 <- plot_ly(economics, x = ~date, y = ~uempmed) p2 <- plot_ly(economics, x = ~date, y = ~unemploy) subplot(p1, p2, p1, p2, nrows = 2, margin = 0.05) #' # anchor multiple traces on the same legend entry p1 <- add_lines(p1, color = I("black"), name = "1st", legendgroup = "1st") p2 <- add_lines(p2, color = I("red"), name = "2nd", legendgroup = "2nd") subplot( p1, style(p1, showlegend = FALSE), p2, style(p2, showlegend = FALSE), nrows = 2, margin = 0.05 ) # or pass a list economics_long %>% split(.$variable) %>% lapply(function(d) plot_ly(d, x = ~date, y = ~value)) %>% subplot(nrows = NROW(.), shareX = TRUE) # or pass a tibble with a list-column of plotly objects economics_long %>% group_by(variable) %>% do(p = plot_ly(., x = ~date, y = ~value)) %>% subplot(nrows = NROW(.), shareX = TRUE) # learn more at https://plotly.com/r/subplots/
This function makes it slightly easier to render TeX in a plotly graph –
it ensures that MathJax is included with the final result and also
ensures the provided string is surrounded with $
(this is what plotly.js
uses to declare a string as TeX).
TeX(x)
TeX(x)
x |
a character vector |
plot_ly(x = c(1, 2, 3, 4), y = c(1, 4, 9, 16)) %>% layout(title = TeX("\\text{Some mathjax: }\\alpha+\\beta x")) %>% config(mathjax = "cdn")
plot_ly(x = c(1, 2, 3, 4), y = c(1, 4, 9, 16)) %>% layout(title = TeX("\\text{Some mathjax: }\\alpha+\\beta x")) %>% config(mathjax = "cdn")
This function makes it possible to convert ggplot2 geoms that are not included with ggplot2 itself. Users shouldn't need to use this function. It exists purely to allow other package authors to write their own conversion method(s).
to_basic(data, prestats_data, layout, params, p, ...)
to_basic(data, prestats_data, layout, params, p, ...)
data |
the data returned by |
prestats_data |
the data before statistics are computed. |
layout |
the panel layout. |
params |
parameters for the geom, statistic, and 'constant' aesthetics |
p |
a ggplot2 object (the conversion may depend on scales, for instance). |
... |
currently ignored |
Convert R colours to RGBA hexadecimal colour values
toRGB(x, alpha = 1)
toRGB(x, alpha = 1)
x |
see the |
alpha |
alpha channel on 0-1 scale |
hexadecimal colour value (if is.na(x), return "transparent" for compatibility with Plotly)
toRGB("steelblue") # [1] "rgba(70,130,180,1)" m <- list( color = toRGB("red"), line = list( color = toRGB("black"), width = 19 ) ) plot_ly(x = 1, y = 1, marker = m)
toRGB("steelblue") # [1] "rgba(70,130,180,1)" m <- list( color = toRGB("red"), line = list( color = toRGB("black"), width = 19 ) ) plot_ly(x = 1, y = 1, marker = m)
Convert trace types to WebGL
toWebGL(p)
toWebGL(p)
p |
a plotly or ggplot object. |
# currently no bargl trace type toWebGL(ggplot() + geom_bar(aes(1:10))) toWebGL(qplot(1:10, 1:10))
# currently no bargl trace type toWebGL(ggplot() + geom_bar(aes(1:10))) toWebGL(qplot(1:10, 1:10))
Description TBD.
wind
wind
A data frame with three variables: r
, t
,
nms
.