R ggplot2 facetting保持比例但覆盖/定义输出图尺寸

时间:2013-10-14 09:57:01

标签: r ggplot2

我目前正在使用ggplot2来比较来自不同组的统计数据,每个组都属于不同的区域。这是通过运行R脚本的Web应用程序(tikiwiki CMS +插件R)完成的。每个区域我可以有2到30个或更多组。同一个R脚本针对唯一网页中的所有数据运行,结果根据所选区域进行调整 - 作为页面的参数。

目前,我有这个:

region 1: 12 groups = 12 medium facets
region 2: 3 groups = 3 **HUGE** facets
region 3: 24 groups = 24 **TINY** facets
region 4: 16 groups = 16 medium facets
...

区域2

Less Groups

区域3

More groups

我希望得到什么样的结果:

区域2

enter image description here

区域3 保持不变

我正在使用 facet_wrap(~data,ncol = 4)对每个组进行分析,因此我可以拥有2个或30个以上的方面。我的问题是输出:要么将30个刻面塞进一个小盒子中,要么将两个刻面尺寸放在相同大小的盒子中 - >看到上面的图片...我找不到如何修复比例(或图像输出最大宽度)但保持最终图片大小免费。

是否可以在ggplot2 / R中修改构面的默认大小,并使得到的图片的大小适应构面的数量?

如果在ggplot2 / R中无法做到这一点,是否有任何javascript / jquery库可以获取代码并正确显示结果(d3,...)?

1 个答案:

答案 0 :(得分:5)

你可以编辑gtable设置高度到物理单位(例如cm)而不是相对(“null”)

require(ggplot2)
p = qplot(Sepal.Width, Sepal.Length, data=iris) + facet_wrap(~Species, ncol=1)
g = ggplotGrob(p)

panels = which(sapply(g[["heights"]], "attr", "unit") == "null")
g[["heights"]][panels] = list(unit(4, "cm"), unit(8, "cm"), unit(2, "cm"))

device.height = convertHeight(sum(g[["heights"]]), "in", valueOnly=TRUE)

pdf("test.pdf", height = device.height)
grid.draw(g)
dev.off()

enter image description here

编辑作为后续工作,此功能可将所有面板的高度和宽度设置为固定值,

freeze_panels <- function(p, draw=TRUE,
                          width=unit(5,"cm"),
                          height=unit(1,"in")){
  require(grid)
  g  <-  ggplotGrob(p)

  vertical_panels <-which(sapply(g[["heights"]], "attr", "unit") == "null")
  horizontal_panels <-which(sapply(g[["widths"]], "attr", "unit") == "null")

  g[["heights"]][vertical_panels] <- replicate(length(vertical_panels), 
                                               height, simplify=FALSE)

  g[["widths"]][horizontal_panels] <- replicate(length(horizontal_panels), 
                                               width, simplify=FALSE)

  device.height  <-  convertHeight(sum(g[["heights"]]), "in", valueOnly=TRUE)
  device.width  <-  convertWidth(sum(g[["widths"]]), "in", valueOnly=TRUE)
  if(draw){
    dev.new(height=device.height, width=device.width)
    grid.newpage()
    grid.draw(g)
  }
  invisible(g)
}



require(ggplot2)
d1 <- subset(mtcars, carb != 8)
d2 <- subset(mtcars, carb %in% c(1,2,3))
p = qplot(vs, am, data=d1) + facet_wrap(~carb)

freeze_panels(p)
freeze_panels(p %+% d2)
freeze_panels(p %+% d2 + facet_wrap(~carb, ncol=1))