将注释框添加到 ggplot 对象的网格中

2024-03-12

我正在准备37个网格ggplot使用grid.arrange功能。节省轴标签当前占用的空间并添加一些信息,例如Sys.time()我会在图形网格的右下角添加一个框。

使用的最小示例mtcars数据可以在下面找到。真实数据将覆盖 x 轴上非常不同的范围,因此无法进行分面。

有没有办法在 R 中添加一个“文本框”(如下面的 *.pdf 所示),以使用例如添加更多信息cat or print?任何提示将不胜感激。

# load needed libraries
library(ggplot2)
library(gridExtra)

# Set loop counter and create list to store objects
imax=37 
plist <- list() 

# loop to generate 37 ggplot objects
# the real example covers different ranges on x-axis so facetting
# is not an option
for(i in 1:imax){
  p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_line()  + ggtitle(i) 
  plist[[i]] <- p
}

# print to pdf in A3 format
pdf(file="out.pdf",width=16.5,height=11.7)
do.call(grid.arrange,c(plist,main="Main Title",sub="Subtitle"))
dev.off()

Update

解决方案通过学得慢 https://stackoverflow.com/a/18911551/891259使用提供的代码Baptiste https://stackoverflow.com/users/471093/baptiste正是我想要的。

实现类似目标的另一种方法是使用annotate_custom()的函数ggplot2在一块空地上。空的意思就是全部theme()属性设置为element_blank()。然后可以使用以下命令将该图排列在网格中以下函数 http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_%28ggplot2%29/由 Winston Chang 在他的 R Cookbook 网站上提供。但是,在此解决方案中,textgrob 不会跨越所有剩余的空 grobs。


基于对巴蒂斯特上述评论的成熟考虑(即我基本上捏碎了他的所有代码),我整理了一个简单的示例。显然,您需要尝试绘图的格式和大小以及textGrob需要在其他地方定义和格式化,但这些都是细节。生成的图如下,代码如下。大部分被占用函数定义 https://gist.github.com/baptiste/6652815情节代码在底部。

gtable_arrange <- function(..., grobs=list(), as.table=TRUE,
                           top = NULL, bottom = NULL, 
                           left = NULL, right = NULL, draw=TRUE){
  require(gtable)
  # alias
  gtable_add_grobs <- gtable_add_grob

  dots <- list(...)
  params <- c("nrow", "ncol", "widths", "heights",
              "respect", "just", "z") # TODO currently ignored

  layout.call <- intersect(names(dots), params)
  params.layout <- dots[layout.call]

  if(is.null(names(dots)))
    not.grobnames <- FALSE else
      not.grobnames <- names(dots) %in% layout.call

  if(!length(grobs))
  grobs <- dots[! not.grobnames ]

  ## figure out the layout
  n <- length(grobs)
  nm <- n2mfrow(n)

  if(is.null(params.layout$nrow) & is.null(params.layout$ncol)) 
  {
    params.layout$nrow = nm[1]
    params.layout$ncol = nm[2]
  }
  if(is.null(params.layout$nrow))
    params.layout$nrow = ceiling(n/params.layout$ncol)
  if(is.null(params.layout$ncol))
    params.layout$ncol = ceiling(n/params.layout$nrow)

  if(is.null(params.layout$widths))
    params.layout$widths <- unit(rep(1, params.layout$ncol), "null")
  if(is.null(params.layout$heights))
    params.layout$heights <- unit(rep(1,params.layout$nrow), "null")

  positions <- expand.grid(row = seq_len(params.layout$nrow), 
                           col = seq_len(params.layout$ncol))
  if(as.table) # fill table by rows
    positions <- positions[order(positions$row),]

  positions <- positions[seq_along(grobs), ] # n might be < ncol*nrow

  ## build the gtable, similar steps to gtable_matrix

  gt <- gtable(name="table")
  gt <- gtable_add_cols(gt, params.layout$widths)
  gt <- gtable_add_rows(gt, params.layout$heights)
  gt <- gtable_add_grobs(gt, grobs, t = positions$row, 
                            l = positions$col)

  ## titles given as strings are converted to text grobs
  if (is.character(top)) 
    top <- textGrob(top)
  if (is.character(bottom)) 
    bottom <- textGrob(bottom)
  if (is.character(right)) 
    right <- textGrob(right, rot = -90)
  if (is.character(left)) 
    left <- textGrob(left, rot = 90)

  if(!is.null(top)){
    gt <- gtable_add_rows(gt, heights=grobHeight(top), 0)
    gt <- gtable_add_grobs(gt, top, t=1, l=1, r=ncol(gt))
  }
  if(!is.null(bottom)){
    gt <- gtable_add_rows(gt, heights=grobHeight(bottom), -1)
    gt <- gtable_add_grobs(gt, bottom, t=nrow(gt), l=1, r=ncol(gt))
  }
  if(!is.null(left)){
    gt <- gtable_add_cols(gt, widths=grobWidth(left), 0)
    gt <- gtable_add_grobs(gt, left, t=1, b=nrow(gt), l=1, r=1)
  }
  if(!is.null(right)){
    gt <- gtable_add_cols(gt, widths=grobWidth(right), -1)
    gt <- gtable_add_grobs(gt, right, t=1, b=nrow(gt), l=ncol(gt), r=ncol(gt))
  }

  if(draw){
   grid.newpage()
   grid.draw(gt)
  }
  gt

}

# load needed libraries
library(ggplot2)

# Set loop counter and create list to store objects
imax=37
plist <- list()
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_line() 

for(i in 1:imax){
  plist[[i]] <- p + ggtitle(i)
}

# build list of grobs
grob.list <- lapply(plist, ggplotGrob)

# prepare titles
title.main <- textGrob("Main title")
title.sub <- textGrob("Subtitle")

# then arrange as required
g <- gtable_arrange(ncol=6, grobs=grob.list, 
                    top=title.main, bottom=title.sub, draw=FALSE)
ann <- grobTree(rectGrob(), textGrob("Annotation box here"))
g <- gtable_add_grobs(g, ann, t=nrow(g)-1, l=2, r=ncol(g))

# save it all together
png(file = "out.png",width=1000, height=710, units = "px")
grid.draw(g)
dev.off()    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将注释框添加到 ggplot 对象的网格中 的相关文章

  • 如何使用 RODBC 将数据帧保存到数据库生成的主键表

    我想使用 R 脚本将数据框输入到数据库中的现有表中 并且希望数据库中的表具有顺序主键 我的问题是 RODBC 似乎不允许主键约束 这是创建我想要的表的 SQL CREATE TABLE dbo results ID INT IDENTITY
  • 带有 geom_errorbar 的position_dodge

    我有以下代码 require ggplot2 pd lt position dodge 0 3 ggplot dt aes x Time y OR colour Group geom errorbar aes ymin CI lower y
  • dmvnorm MVN 密度 - RcppArmadillo 实现比 R 包慢,包括一些 Fortran

    The solution现已上线RCPP画廊 http gallery rcpp org articles dmvnorm arma 我从 RcppArmadillo 中的 mvtnorm 包重新实现了 dmvnorm 我有点喜欢犰狳 但我
  • r caret 包中的 train 函数的模型输出尺寸巨大

    我正在使用 bagFDA 模型进行训练train r caret 包中的函数 并将模型输出保存为 Rdata 文件 输入文件大约有 300k 条记录 有 26 个变量 但输出 Rdata 大小为 3G 我只是运行以下命令 modelout
  • 使用 X11 窗口的 R 脚本仅打开一秒钟

    我正在通过 Linux Mint 16 命令行运行 R 脚本 它包含我想在窗口中显示的箱线图 所以我使用 x11 函数来创建该窗口 这是我的代码 testdata lt data frame sample 1 1000 size 100 r
  • 在 R 中使用 gsub 删除尾随空格[重复]

    这个问题在这里已经有答案了 有没有人有一个技巧可以用 gsub 删除变量上的尾随空格 以下是我的数据示例 正如您所看到的 我在变量中同时包含尾随空格和嵌入空格 county lt c mississippi mississippi cany
  • 根据另一个向量替换向量中的值

    我想替换向量中的值 x 与另一个向量 y 陷阱 22 方法需要是动态的 以适应向量中不同数量的 级别 x 例如 考虑向量x x lt sample c 1 2 3 4 5 100 replace TRUE gt x 1 2 4 1 1 3
  • 为什么我必须在每次 R 升级时手动创建目录“~/R/%p-library/%v”?

    每次R升级后 我必须重新安装我使用的软件包 来自源代码 因此必须为新版本重新编译它们 这是一个正确的 可以理解的行为 所以我调用install packages http stat ethz ch R manual R devel libr
  • 列槽不足

    当尝试为 data table 中的每个变量 108 个变量 创建 12 个滞后时 我收到一条错误 指出列槽不足 此操作应创建大约 1200 个变量或列 Data A as data table Datos A Varnames names
  • 按列分组的数据帧上 R 中的行之间的差异

    我希望通过 app name 获得不同版本的计数差异 我的数据集如下所示 app name version id count difference 这是数据集 data structure list app name structure c
  • 在 R 中使用 spplot 将多个绘图放在一个页面上?

    我知道如何在使用简单函数图时绘制两个图 old par lt par mfrow c 1 2 plot faithful main Faithful eruptions plot large islands main Islands yla
  • 修复 ggplot 中构面中的数据顺序

    我在使用 ggplot 绘制数据时遇到问题 我无法使每个方面内的数据正确排序 我的样本数据是 data lt structure list Parameter c 0 1 0 7 0 0 0 2 0 2 0 7 0 0 0 1 0 3 0
  • 删除 R 中具有重复属性的行

    我有一个大数据框 其中包含以下列 ID time OS IP 该数据帧的每一行对应一个条目 在该数据框中对于某些IDs存在多个条目 行 我想删除这些多行 显然 同一 ID 的其他属性会有所不同 或者换句话说 我只想要每个 ID 一个条目 行
  • 使用 R 读取和转换二进制原始数据

    我有一个file https drive google com file d 0BxMpk0nhnJy6SFhxd2xuMzJYYlk edit usp sharing其中包含原始 二进制数据和 ascii 它包含一个时间戳和一个代表速度的
  • 按具有作业的组划分的 R 分位数

    我有以下 df group rep seq 1 3 30 variable runif 90 5 0 7 5 df data frame group variable 我需要 i 按组定义分位数 ii 将每个人分配到相对于其组的分位数 因此
  • 建模前减少因子水平数量

    我有一个 2600 个级别的因子 我想在建模之前将其减少到 10 我想我可以通过这样的操作来做到这一点 如果一个因素列出的次数少于 x 次 则应将其放入名为 其他 的存储桶中 这是一些示例数据 df lt data frame colour
  • 抑制 R 中的错​​误消息

    我正在 R 中运行模拟研究 有时 我的模拟研究会产生错误消息 当我在函数中实现模拟研究时 当出现此错误消息时模拟停止 我知道抑制错误是不好的做法 但此时对我来说 除了抑制错误然后继续下一个模拟 直到达到我喜欢运行的模拟总数为止 没有其他选择
  • 在ggplotly散点图中添加自定义数据标签

    我想显示Species对于每个数据点 当光标位于该点上方而不是 x 和 y 值时 我用iris数据集 另外 我希望能够单击数据点以使标签持久存在 并且当我在图中选择新位置时标签不会消失 如果可能的话 最基本的是标签 持久性问题是一个优点 这
  • 对于多项式,获取其所有极值并通过突出显示所有单调部分来绘制它

    有人问我这个有趣的问题 我认为值得将其发布在这里 因为 Stack Overflow 上还没有任何相关线程 假设我有长度为的多项式系数n vector pc 其中次数多项式n 1对于变量x可以以其原始形式表示 pc 1 pc 2 x pc
  • 从 R 到 C 处理列表并访问它

    我想使用从 R 获得的 C 列表 我意识到这个问题与此非常相似 使用 call 在 R 和 C 之间传递数据帧 https stackoverflow com questions 6658168 passing a data frame f

随机推荐