R:如何使用唯一 ID 在图形中绘制多个图

R: How to make multiple plots in a graph using unique IDs

我有一个数据框 df 有 4 个唯一 UID - 1001,1002,1003,1004.

我想在 R 中编写一个 user-defined function 来执行以下操作:

  1. 针对每个唯一 UID 针对 Time 绘制 Turbidity。浊度值是 Time_1Time_2Time_3 列中的值。例如,UID = 1001 将在一张图中有 4 个绘图

  1. 为每个图表添加图例,例如 M-LF-LM-RF-R(来自 Gen 列和 Type)

  2. 为每个图表添加标题。例如- UID:1001

  3. 将图表导出为 pdf 或 jpeg 或 tiff pdf 文件 - 每页 4 个图表

# dataset
Gen <- c('M','M','M','M','F','F','F','F','M','M','M','M','F','F','F','F')
Site <- rep('FRX',length(gen))
Type <- c('L','L','L','L','L','L','L','L','R','R','R','R','R','R','R','R')
UID <- c(1001,1002,1003,1004,1001,1002,1003,1004,1001,1002,1003,1004,1001,1002,1003,1004)
Time_1 <- c(100.78,112.34,108.52,139.19,149.02,177.77,79.18,89.10,106.78,102.34,128.52,119.19,129.02,147.77,169.18,170.11)
Time_2 <- c(150.78,162.34,188.53,197.69,208.07,217.76,229.48,139.51,146.87,182.54,189.57,199.97,229.28,247.73,269.91,249.19)
Time_3 <- c(250.78,262.34,288.53,297.69,308.07,317.7,329.81,339.15,346.87,382.54,369.59,399.97,329.28,347.73,369.91,349.19)
df <- data.frame(Gen,Site,Type,UID,Time_1,Time_2,Time_3)
df

我的尝试

library(ggplot2)
library(tidyr)

# See below for my thoughts/attempt- I am open to other R libraries and approaches

graphplotter <-function(x){
    # 1. Convert from wide to long
    data_long <- gather(df, time, turbidity, Time_1:Time_3, factor_key=TRUE)
    data_long
    #2. plot for each unique UID- 1001 to 1004 and add legend
    basic <- ggplot(datalong, aes(time, turbidity, shape=Tree)) + geom_point() + geom_line()
    basic + theme(
    legend.position = c(.95, .95),
    legend.justification = c("right", "top"),
    legend.box.just = "right",
    legend.margin = margin(6, 6, 6, 6))
    #3. add title
    print(basic+ labs( title= "UID: 1001, Tubidity against time", y="turbidity", x = "Time in hours"))
    #4. export as pdf
    pdf("turbdity-time.pdf")
    par(mfrow = c(2, 2))  ## set the layout to be 2 by 2
    sapply(1:4, function(i) plot(basic[,i]))
    dev.off()
}

我希望所有四个图表看起来像这样(忽略周长和年龄,应该是浊度和时间)。

谢谢

我用facet_wrap

graphplotter <-function(x){
  x %>%
    gather(., time, turbidity, Time_1:Time_3, factor_key=TRUE) %>%
    mutate(label = (paste0(Gen, "-", Type))) %>%
    #group_by(UID) %>%
    ggplot(aes(color = label)) + geom_point(aes(time, turbidity, shape = label, group = label)) +
    geom_line(aes(time, turbidity, group = label)) + facet_wrap(~UID) + theme(
      legend.position = c(1, 1),
      legend.justification = c("right", "top"),
      legend.box.just = "right",
      legend.margin = margin(1, 1, 1, 1),
      legend.text = element_text(size = 7))
}

graphplotter(df)