Ryan
Ryan

Reputation: 1068

How to include unique grouping variables in plot titles and file names when using plotly?

I am learning to use plotly. I have a data set similar to data created below. The .html plots created using the code below work as I want them to; a unique "interactive" plot is created for each unique ID. However, I am having trouble incorporating my grouping variable Group. I would like for the name of the grouping variable to be included in the title of each plot, and the name of each file. For instance, the title of the plot created below will say "plot_for_ID_A". I want it to say "plot_for_Alpha_A", with Alpha referring to the grouping variable. I have tried multiple things in the paste function, I have tried putting filter(group==.y) under the filter() call so that I can refer to .y in the paste() call, and several other things that didn't work. What is the best way to do this?

library(tidyverse)
library(plotly)

ID <- rep(c("A","B","C","D","E","F"), each=1000)
Group <- rep(c("alpha","beta"), each = 3000)
time <- rep(c(1:1000), times = 6)
one <- rnorm(6000)
two <- rnorm(6000)  
three <- rnorm(6000)
four <- rnorm(6000)
five<-rnorm(6000)
data <- data.frame(cbind(ID,Group,time,one,two,three,four,five),
                  stringsAsFactors = FALSE)

data_long <- data %>%
pivot_longer(-c(ID:time), names_to="Variable", values_to="Value")%>% 
  mutate(time = as.numeric(time),
         value = as.numeric(Value))


walk(unique(data_long$ID),
    ~ htmlwidgets::saveWidget(ggplotly(data_long %>% 
                                filter(ID == .x) %>% 
                                ggplot(aes(x = time, 
                                           y = value, 
                                           color = Variable)) +
                                geom_point() +
                                labs(title = paste(.x))),
                              paste("plot_for_ID_", .x, ".html", sep = "")))

Also, the output of this code creates a unique .html file for each plot. Is there a way to paste all the plots into a single file where each plot has its own page?

Upvotes: 0

Views: 215

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

You could use group_split to split data based on groups and get the name of the plot from it's columns values.

library(tidyverse)
library(plotly)

data_long %>%
  group_split(ID, Group) %>%
  map(~ htmlwidgets::saveWidget(ggplotly(
                                  ggplot(.x, aes(x = time, 
                                                 y = value, 
                                              color = Variable)) +
                                   geom_point() +
               labs(title = paste0("plot_for_", .x[[2]][1], "_", .x[[1]][1]))),
               paste0("plot_for_", .x[[2]][1], "_", .x[[1]][1], ".html")))

Upvotes: 2

Related Questions