使用plotly时如何在绘图标题和文件名中包含唯一的分组变量?

问题描述 投票:0回答:1

我正在学习使用plotly。我有一个类似于下面创建的data的数据集。使用下面的代码创建的.html图可以按我的要求工作;为每个唯一的ID创建一个唯一的“交互”图。但是,在合并分组变量Group时遇到问题。我希望分组变量的名称包含在每个图的标题中,以及每个文件的名称中。例如,下面创建的图的标题将显示为"plot_for_ID_A"。我想说"plot_for_Alpha_A",其中Alpha指的是分组变量。我在粘贴函数中尝试了多种方法,尝试将filter(group==.y)放在filter()调用下,以便可以在.y调用中引用paste(),以及其他一些无效的方法。最好的方法是什么?

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 = "")))

此外,此代码的输出还会为每个图创建一个唯一的.html文件。有没有一种方法可以将所有图粘贴到单个文件中,其中每个图都有自己的页面?

r ggplot2 iteration plotly paste
1个回答
0
投票

您可以使用group_split基于组拆分数据,并从其列值中获取图的名称。

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")))
© www.soinside.com 2019 - 2024. All rights reserved.