[英]How to include unique grouping variables in plot titles and file names when using plotly?
我正在学习使用plotly
。 我有一个数据集类似data
下创建。 使用下面的代码创建的 .html 图可以按照我的意愿工作; 为每个唯一ID
创建一个唯一的“交互式”图。 但是,我无法合并我的分组变量Group
。 我希望在每个图的标题中包含分组变量的名称,以及每个文件的名称。 例如,下面创建的图的标题将显示"plot_for_ID_A"
。 我希望它说"plot_for_Alpha_A"
, Alpha
指的是分组变量。 我在 paste 函数中尝试了多种方法,我尝试将filter(group==.y)
放在filter()
调用下,以便我可以在paste()
调用中引用.y
,以及其他一些没有的东西工作。 做这个的最好方式是什么?
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 文件。 有没有办法将所有图粘贴到一个文件中,每个图都有自己的页面?
您可以使用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")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.