通过 Dataframe 列表进行ggplot的函数:添加标题

rqdpfwrv  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(92)

我写了一个函数来绘制 Dataframe 列表。

library(dplyr)
library(tidyr)
library(ggplot2)
#function to plot each df in list
func.plot <- function(x){

ggplot(data = x, aes(x = month)) + 
    geom_line(aes(y = MFI, group = sample), color = "lightgrey", size = 0.5)+ 
    geom_line(aes( y = mean), color = "red", size = 2) + 
    theme_bw()+ 
    ggtitle("for non-recurrent infections")
  }

#apply function to list
lapply(test, func.plot)

我很难得到每个情节的 Dataframe 特定的标题。我希望每个情节的标题是“非复发性感染的 Dataframe 名称”。
我已经尝试了一些想法的ggtitle行,如

ggtitle(x, "for non-recurrent infections")

    ggtitle(paste0(x), "for non-recurrent infections")

然而,这些都不起作用。任何帮助都将不胜感激。
此外-任何提示打印输出并排(也许8到一个绘图)也将不胜感激!
样本数据:

CSP1: 

structure(list(sample = c(35L, 35L, 35L, 35L, 35L, 35L), month = c(0, 
0.25, 1, 2, 3, 4), MFI = c(228.6666667, 160.6666667, 226.6666667, 
131.6666667, 170.1666667, 115.1666667), mean = c(1013.04700847142, 
1499.62393155462, 697.698717902436, 437.448717901244, 599.012820505269, 
619.978632424128)), class = c("grouped_df", "tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -6L), groups = structure(list(
    month = c(0, 0.25, 1, 2, 3, 4), .rows = structure(list(1L, 
        2L, 3L, 4L, 5L, 6L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .drop = TRUE))

PvRBP2b: 
    structure(list(sample = c(35L, 35L, 35L, 35L, 35L, 35L), month = c(0, 
0.25, 1, 2, 3, 4), MFI = c(18823, 22188, 15356, 7536, 5372, 2177.5
), mean = c(10131.0427347736, 15102.9273501617, 11751.3803417424, 
11039.9935895637, 11553.0448715292, 9797.237179345)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L), groups = structure(list(
    month = c(0, 0.25, 1, 2, 3, 4), .rows = structure(list(1L, 
        2L, 3L, 4L, 5L, 6L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .drop = TRUE))

test <- list(CSP1, PvRBP2b)
pdkcd3nj

pdkcd3nj1#

一种选择是使用一个名为list的变量(我使用dplyr::lst),然后使用purrr::imap,它将该变量名作为第二个参数传递给函数,当然也可以添加第二个参数给绘图函数:

library(dplyr, warn=FALSE)
library(ggplot2)

test <- dplyr::lst(CSP1, PvRBP2b)

func.plot <- function(x, name) {
  ggplot(data = x, aes(x = month)) +
    geom_line(aes(y = MFI, group = sample), color = "lightgrey", size = 0.5) +
    geom_line(aes(y = mean), color = "red", size = 2) +
    theme_bw() +
    ggtitle(paste(name, "for non-recurrent infections"))
}

purrr::imap(test, func.plot)
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` instead.
#> $CSP1

#> 
#> $PvRBP2b

相关问题