【问题标题】:ggplot, plotting in multiple pages with different rowsggplot,在具有不同行的多个页面中绘图
【发布时间】:2016-02-07 11:09:13
【问题描述】:

我想使用facet_wrap 制作图表并将其绘制在 pdf 文件的不同页面中。我读过儿子很多选择,这很有效: R + ggplot: plotting over multiple pages 但仅当您在每个页面中具有相同的行时。

我有这个演示数据来解释我的案例:

A <- data.frame(TIME = rep(c(0, 5, 10, 15, 30, 45, 60), 5))
A$C <- (1 - exp(-0.2*A$TIME))
A$ID <- rep(1:5, each = 7)
A$R <- rnorm(35, mean = 1, sd = 0.01)
A$C2 <- A$C*A$R
Pages <- 5
A2 <- A[c(1,4:8,10:22,24:35),]

所以,我有不同数量的观察 ID。我试图用每个 ID 中的观察次数制作一个向量(我想要每页一个 ID),但它不起作用。

nrws <- ddply(A2, .(ID), "nrow")
nsamp <- nrws[,2]

pdf("Test.pdf")
for (i in seq(Pages))
  {
    slice = seq(((i-1)*nsamp[i]),(i*nsamp[i]))
    slice2 = slice[!(slice > nrow(A2))]
    A3 = A2[slice2,]
    p1 <- ggplot(A3, aes(x = TIME, y = C2)) +  
      geom_line(size = 0.5) +
      geom_point(size = 1) +
      facet_wrap(~ID)
print(p1)
  }
dev.off()

你能帮帮我吗?

提前致谢, 纳乔

【问题讨论】:

    标签: r loops pdf ggplot2 facet-wrap


    【解决方案1】:

    我认为您在计算“切片”时想多了。也许你想要这个?

    不完全确定。如果您只希望每页有一个 ID,则不需要 facet_wrap,您可能需要明确设置比例以保持每页的比例相同。

    library(plyr)
    
    A <- data.frame(TIME = rep(c(0, 5, 10, 15, 30, 45, 60), 5))
    A$C <- (1 - exp(-0.2*A$TIME))
    A$ID <- rep(1:5, each = 7)
    A$R <- rnorm(35, mean = 1, sd = 0.01)
    A$C2 <- A$C*A$R
    Pages <- 5
    A2 <- A[c(1,4:8,10:22,24:35),]
    
    nrws <- ddply(A2, .(ID), "nrow")
    nsamp <- nrws[,2]
    
    pdf("Test.pdf")
    for (i in seq(Pages))
    {
    #  slice = seq(((i-1)*nsamp[i]),(i*nsamp[i]))
    #  slice2 = slice[!(slice > nrow(A2))]
    #  A3 = A2[slice2,]
    
      A3 = A2[A2$ID==i,]
      p1 <- ggplot(A3, aes(x = TIME, y = C2)) +  
        geom_line(size = 0.5) +
        geom_point(size = 1) +
        facet_wrap(~ID)
      print(p1)
    }
    dev.off()
    

    【讨论】:

    • 你是对的,你的解决方案(比我的简单)我不需要 facet_wrap。非常感谢!!
    • 您可能需要使用 scale_y_continuous 明确设置 y 范围,否则它会因页面而异,并且难以比较。这是facet_wrap 自动为您执行的操作,但仅在给定的ggplot 调用中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多