【问题标题】:Segment facet_wrap into multi-page PDF将 facet_wrap 分割成多页 PDF
【发布时间】:2014-05-24 16:24:14
【问题描述】:

我已经四处寻找解决方案,但似乎大多数处理将单独生成的图组合成 PDF 格式,而不是将使用分面生成的图分离到 PDF 的单独页面上。

Example Data

在上述数据中使用如下代码,选择生成列表中的所有项目:

Ex<-read.csv("StackOverflowEx (3).csv")
library(ggplot2)
library(reshape2)
vars <- select.list(names(Ex),multiple=TRUE,graphics=TRUE)
Cases<-subset(Ex,select=vars)

gg<-melt(Cases,id=c("Item","Total","Admin"))
print(ggplot(gg, aes(x=Total,y=Admin))+
  geom_point(colour="dark green",size=1.5)+
  geom_point(aes(y=value,color=variable))+
  geom_smooth(aes(y=value,fill=variable),
              method=loess,size=1,linetype=1,se=T)+
  facet_wrap(~variable,ncol=2,nrow=1000)+
  ylim(0,1)+
  labs(x="Expected",y="Admin",title=vars))

...应该生成所有 8 个 (A-H) 案例的分面包装。然而,生成这个往往会限制图并降低它们的可读性,实际上,我打算在 500 多个案例中使用它(它只返回标有列名的条形图,没有可读的图表)。

是否可以在转换为 PDF 时指定分面中显示在单个页面上的图表数量,而不是将所有图表压缩到单个页面中?例如,使用上述数据,在单独的页面上生成两个 2x2 图,分别包含所有 8 个案例(即第 1 页上的案例 A-D,第 2 页上的案例 E-H)。

我可以通过突出显示 4 个案例 +“项目”、“总计”和“管理员”并重复接下来的 4 个案例并合并生成的 PDF 来做到这一点。然而,在实践中超过 500 个案例,这将意味着超过 100 次迭代,并且有很多人为错误的可能性。一些自动化流程的帮助会很棒。

【问题讨论】:

  • 如果您搜索marrangeGrob,您可能会发现一些想法,例如here
  • Hadley 建议手动干预in 2011。我会尝试找出# facets/pg 的工作原理,然后将循环或“应用”在n 之间pdf(…)dev.off() 调用之间。
  • 我会循环遍历 4 或 5 个一组的 500 个变量,然后为每个变量生成一个图表,将所有变量转储为 pdf。我最近做了类似的事情,我使用循环在每页生成 4 个图,并在每个 pdf 页面中使用 grid.arrange 绘制 4
  • 都非常有帮助。不幸的是,我的理解力超出了我的编码能力,所以到目前为止我的努力并没有什么成果。
  • 帖子顶部的数据链接当前受到保护。如果复制示例不依赖于发送访问 Google Drive 上该信息的权限请求,将对未来的用户有所帮助。

标签: r pdf ggplot2 facet-wrap


【解决方案1】:

因为还没有答案。这是一个:

library(ggplot2)
library(reshape2)

Ex <- read.csv("C:/Users/Thomas/Desktop/StackOverflowEx (3).csv")
gg <- melt(Ex,  id = c("Item", "Total", "Admin"))

# put in number of plots here
noPlots <- 4
# save all variables in a seperate vector to select in for-loop
allVars <- unique(gg$variable)
noVars <- length(allVars)

# indices for plotting variables
plotSequence <- c(seq(0, noVars-1, by = noPlots), noVars)

# pdf("plotpath.pdf") # uncomment to save the resulting plots in a pdf file
# loop over the variables to plot
for(ii in 2:length(plotSequence)){
  # select start and end of variables to plot
  start <- plotSequence[ii-1] + 1
  end <- plotSequence[ii]

  # subset the variables and save new temporary data.frame
  tmp <- subset(gg, variable %in% allVars[start:end])
  cat(unique(tmp$variable), "\n")

  # generate plot
  p <- ggplot(tmp,  aes(x = Total, y = Admin))+
    geom_point(colour = "dark green", size = 1.5)+
    geom_point(aes(y = value, color = variable))+
    geom_smooth(aes(y = value, fill = variable), 
                method = loess, size = 1, linetype = 1, se = T)+
    facet_wrap(~variable, ncol = 2, nrow = 1000)+
    ylim(0, 1)+
    labs(x = "Expected",  y = "Admin")
  print(p)
}
# dev.off()

【讨论】:

  • 哇。谢谢你。我把这个项目放在了次要位置,但你的代码完全符合我的要求。再次,非常感谢。
猜你喜欢
  • 2020-02-08
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多