【问题标题】:Adding tables to ggplot2 with facet_wrap in r在 r 中使用 facet_wrap 将表添加到 ggplot2
【发布时间】:2018-03-25 11:17:33
【问题描述】:

我想添加一个表格,其中包含一些信息,这些信息在构面内的每个面板中都会有所不同。 我正在使用 ggplot2 和 facet_grid。

假设我想为每个面板添加某种描述性统计信息,但它们不一定相同。 这些统计信息放在我为此目的制作的 df 中。

我找到了一些将这些表格添加到图表中的方法,但是:

  1. 就我而言,Annotate 会为我在 facet 中的所有面板提供同一张表。
  2. 为了简单起见,我真的很想使用 facet_warp 而不是 grid_extra...
library(datasets)
data(mtcars)
ggplot(data = mpg, aes(x = displ, y = hwy, color = drv)) +
    geom_point() +
    facet_wrap( ~ cyl,scales="free_y")

表格的位置对我来说并不重要,但我不希望它与图表重叠。

我的目标是该线程中两个答案的混合: Adding table to ggplot with facets

第一个答案(带有注释)对我不起作用,因为我希望每个情节中的表格都是唯一的。) 第二个答案更好,但我不希望它重叠或隐藏图表中的一些细节,并且在每个面板中,线/散点位于不同的位置,所以我不能那样使用它。我希望它像在注释中一样附加。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

试试这个

library(ggplot2)
library(tibble)
library(gridExtra)
library(grid)

GeomCustom <- ggproto(
  "GeomCustom",
  Geom,
  setup_data = function(self, data, params) {
    data <- ggproto_parent(Geom, self)$setup_data(data, params)
    data
  },

  draw_group = function(data, panel_scales, coord) {
    vp <- grid::viewport(x=data$x, y=data$y)
    g <- grid::editGrob(data$grob[[1]], vp=vp)
    ggplot2:::ggname("geom_custom", g)
  },

  required_aes = c("grob","x","y")

)

geom_custom <-  function(mapping = NULL,
           data = NULL,
           stat = "identity",
           position = "identity",
           na.rm = FALSE,
           show.legend = NA,
           inherit.aes = FALSE,
           ...) {
    layer(
      geom = GeomCustom,
      mapping = mapping,
      data = data,
      stat = stat,
      position = position,
      show.legend = show.legend,
      inherit.aes = inherit.aes,
      params = list(na.rm = na.rm, ...)
    )
}


gl <- list(tableGrob(iris[1:2,1:3]), 
           tableGrob(iris[1:4,1:3]),
           tableGrob(iris[1:3,1:3]),
           tableGrob(iris[1:2,1:2]))

dummy <- tibble(f=letters[1:4], grob = gl )

d <- tibble(x=rep(1:3, 4), f=rep(letters[1:4], each=3))

ggplot(d, aes(x,x)) +
  facet_wrap(~f) +
  theme_bw() +
  geom_custom(data=dummy, aes(grob=grob), x = 0.5, y = 0.5)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-25
    • 2021-10-25
    • 2019-08-04
    • 1970-01-01
    • 2016-01-10
    • 2013-12-21
    • 1970-01-01
    相关资源
    最近更新 更多