r - 将facet_wrap分割成多页PDF

标签 r pdf ggplot2 facet-wrap

我一直在寻找解决方案,但是似乎大多数处理都是将单独生成的图合并为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时,是否可以指定刻面中要显示在单个页面上的图表数量,而不是将所有图压缩到单个页面中?例如,使用上述数据,在分别包含所有8个案例的单独页面上生成两个2x2绘图(即第1页的案例A-D,第2页的案例E-H)。

我可以通过突出显示4个案例+“项目”,“总计”和“管理员”,然后对接下来的4个案例重复并组合生成的PDF来完成此操作。但是,在实践中,如果有500多个案例,这将意味着进行100多次迭代,并且有很多潜在的人为错误。自动化过程的一些帮助将非常有用。

最佳答案

由于尚无答案。这是一个:

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()

关于r - 将facet_wrap分割成多页PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22996911/

相关文章:

r - 更改 R 中的内部因子水平(对于避风港很重要 - write_dta())

pdf - 在 Latex 中包含图像时出错

pdf - 是否有将 swagger json 转换为 PDF for HTML 的公共(public)网站?

r - ggplot2 : Add a gradient colored square according to values

r - 如何格式化ggplot2图例的数值?

r - 使用 R 将比例尺插入 map

r - 使用scale_shape_manual时图例中的颜色丢失

c# - 如何在 C# 中通过 POST HttpWebRequest 发送 PDF

r - 使用ggplot2中的scale_fill_brewer()函数设置数据断点

r - R 中的多次重复(2 次、3 次、...)