Basil
Basil

Reputation: 1004

Create dataframe of plotlys in R

I have been using the below code to create a df of plotlys in R.

In this example, one plotly for each species from the iris dataset.

However the do function from dplyr has been superceeded so want to update the code.

library(plotly)
library(tidyverse)

plots<-. %>%
plot_ly(x = ~Sepal.Length, y = ~Petal.Length)%>%
add_markers()

df_plotly<-iris%>%
   group_by(Species)%>%
   do(plotly_objects=(plots(.)))

The documentation says replace do with summarise, nest_by and across however I can't see how to apply those functions to this code.

How can I rewrite the above code to replace the do function?

Upvotes: 1

Views: 34

Answers (2)

Basil
Basil

Reputation: 1004

This is how I ultimately ended up solving this problem:

library(plotly)
library(tidyverse)

plots<-. %>%
  plot_ly(x = ~Sepal.Length, y = ~Petal.Length)%>%
  add_markers()

df_plotly<-iris %>%
  nest_by(Species,.key = "nested_data") %>%
  mutate(p = list(plots(nested_data)))

Upvotes: 0

Andy Baxter
Andy Baxter

Reputation: 7626

With a little bit of reformatting this works well using purrr::nest and dplyr::mutate:

library(plotly)
library(tidyverse)

plots<-. %>%
  plot_ly(x = ~Sepal.Length, y = ~Petal.Length)%>%
  add_markers()

df_plotly <- iris %>%
  nest(data = -Species) %>%
  rowwise() %>%
  mutate(plotly_objects = list(plots(data)))

df_plotly
#> # A tibble: 3 × 3
#> # Rowwise: 
#>   Species    data              plotly_objects
#>   <fct>      <list>            <list>        
#> 1 setosa     <tibble [50 × 4]> <plotly>      
#> 2 versicolor <tibble [50 × 4]> <plotly>      
#> 3 virginica  <tibble [50 × 4]> <plotly>

Upvotes: 1

Related Questions