Reputation: 555
In the example below, is there anyway to store the main plotly built component as an object:
library(magrittr)
library(plotly)
## this works
mtcars %>%
plot_ly(
x = ~mpg,
y = ~hp,
type = "scatter",
mode = "markers"
)
## this doesn't work
plot_object <- plot_ly(
x = ~mpg,
y = ~hp,
type = "scatter",
mode = "markers"
)
mtcars %>%
plot_object
Upvotes: 0
Views: 41
Reputation: 15462
The problem with this:
plot_object <- plot_ly(
x = ~mpg,
y = ~hp,
type = "scatter",
mode = "markers"
)
is that it's dependent on the mtcars
data, but it is not used here as in your first example.
So you could do this instead:
plot_object <- mtcars %>% plot_ly(
x = ~mpg,
y = ~hp,
type = "scatter",
mode = "markers"
)
If this about being able to reuse the plot, but with different data you could make it a function and pass the data as parameters.
Update
A generic function could look something like this:
plot_object <- function(x, y) {
plot_ly(
x = x,
y = y,
type = "scatter",
mode = "markers"
)
}
plot_object(mtcars$mpg, mtcars$hp)
Upvotes: 2