【问题标题】:saving each modified facet in ggplot2将每个修改的方面保存在 ggplot2
【发布时间】:2017-11-08 00:29:01
【问题描述】:

我尝试使用for loop 将虹膜数据集中的每个Species 数据保存为.png 文件。但在此之前,我想在实际数据绘图过程中修改刻面带厚度。

但是,当我尝试编写每个方面时 下面的代码只是给了我每个物种的空图。

这是我的尝试,

library(ggplot2)
plot_list = list()
for (i in unique(iris$Species)) {
  p = ggplot(iris[iris$Species == i, ], aes(x=Sepal.Length, y=Sepal.Width)) +
    geom_point(size=3, aes(colour=Species))+
    facet_wrap(~Species)

#this part to modify facet_wrap strips
  g1 = ggplotGrob(p)

  pos =  c(unique(subset(g1$layout, grepl("panel", g1$layout$name), select = t)))
  for(i in pos) g1$heights[i-1] = unit(0.4,"cm")

  grobs = which(grepl("strip", g1$layout$name))
  for(i in grobs) g1$grobs[[i]]$heights <-  unit(1, "npc") 

  grid.newpage()
  grid.draw(g1)
  plot_list[[i]] = g1
}

#finally write the modified graphs to file


for (i in 1:3) {
  file_name = paste("iris_plot_", i, ".png", sep="")
  tiff(file_name)
  print(plot_list[[i]])
  dev.off()
}

目前这段代码正在生成空图,不知道为什么!任何帮助将不胜感激!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您无需使用ggplotGrob 修改条带高度。在 ggplot 的 theme() 中设置相关参数即可:

    p1 = ggplot(iris[iris$Species == "setosa",],
                aes(x = Sepal.Length, y = Sepal.Width)) +
      geom_point() +
      facet_wrap(~Species)
    
    p2 = p1 + theme(strip.text.x = element_text(margin = margin(t = 10, b = 10)))
    # note: default margin for top & bottom is 5.5
    
    gridExtra::grid.arrange(p1, p2, ncol = 2)
    

    至于其余部分,您可能希望在第一个循环之后检查plot_list 的长度。您最初分配 i 以获取 iris$Species 的唯一值,然后尝试将其用作绘图列表的索引。 plot_list 的前三个元素不包含绘图。

    以下内容适用于本示例。您可能需要针对实际用例进行一些修改:

    plot_list = list()
    loop.list <- unique(iris$Species)
    for (i in seq_along(loop.list)) {
      p = ggplot(iris[iris$Species == loop.list[i], ], 
                 aes(x = Sepal.Length, y=Sepal.Width)) +
        geom_point(size = 3, aes(colour = Species))+
        facet_wrap(~Species) +
        theme(strip.text.x = element_text(margin = margin(t = 11, b = 11)))
    
      plot_list[[i]] <- ggplotGrob(p)
    }
    
    for (i in 1:3) {
      file_name = paste("iris_plot_", i, ".png", sep="")
      tiff(file_name)
      grid.draw(plot_list[[i]])
      dev.off()
    }
    

    【讨论】:

    • 嗨。感谢 cmets 和您的解决方案。实际上,我知道设置文本大小是一种解决方案,但不是我所经历的正确方式。因为当你有很多方面并且你把条形文本做得非常小时,很难看到条形文本。转身方法是像我的 OP 代码中那样细化条带。
    • 我在 [这里] stackoverflow.com/questions/36783189/…987654322@ 询问过
    • @Alexander 如果您想继续在 grob 对象中进行更改,只需保持循环计数器正常。一种方法(如上所示)是让i 采用unique(iris$Species) 中每个值的索引而不是值本身,如果您在此循环中有更多循环,请使用不同的计数器,例如j.
    • 很抱歉。当更改循环ggplotGrob 的索引值时,您是对的,问题已解决。感谢您的建议和解决方案。
    猜你喜欢
    • 2015-04-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2013-06-20
    相关资源
    最近更新 更多