【问题标题】:How to add a table to a ggplot?如何将表格添加到ggplot?
【发布时间】:2020-02-22 04:24:12
【问题描述】:

我正在尝试将常规 ggplot 图表与使用 flextable 获得的表格组合(在单个图表中)。

考虑以下示例:

library(tidyverse)
library(patchwork)

mydf <- tibble(a = c(1,2,3,4,5,4),
               b = c(4,4,4,3,3,3))

p1 <- mydf %>% ggplot(aes(x = a, y = b, color = as.factor(b))) + geom_point()

p2 <- mydf %>% flextable::flextable()

p2 看起来像

但不幸的是我不能将它与p1结合起来

> p1 + p2
Error: Don't know how to add p2 to a plot

我们能做什么? 谢谢!

【问题讨论】:

标签: r ggplot2 flextable patchwork


【解决方案1】:

您可以使用函数 flextable::as_raster 从弹性表中获取栅格,然后使用 annotation_custom 添加到空的 ggplot 对象。

library(ggplot2)
library(flextable)
library(grid)
library(cowplot)
library(tidyverse)

mydf <- tibble(a = c(1,2,3,4,5,4),
               b = c(4,4,4,3,3,3))

p1 <- mydf %>% ggplot(aes(x = a, y = b, color = as.factor(b))) + geom_point()

ft_raster <- mydf %>% flextable::flextable() %>% 
  as_raster()

p2 <- ggplot() + 
  theme_void() + 
  annotation_custom(rasterGrob(ft_raster), xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)

cowplot::plot_grid(p1, p2, nrow = 2, ncol = 1, rel_heights = c(4, 1) )

文档在这里:https://davidgohel.github.io/flextable/articles/offcran/images.html

【讨论】:

  • 谢谢!!但我试图添加表格,就好像它是一个情节(而不是作为注释)。我怎么能得到那个?
  • 换句话说,表格应该占用与绘图一样多的空间(并排)
  • 如果我理解正确,拼凑,你将不得不使用p1 + p2 或cowplot cowplot::plot_grid(p1, p2, nrow = 1, ncol = 2)。这就是你想要的吗?
  • 哈实际上大卫最大的问题是 as_raster 需要 install_phantomjs() 已被弃用且难以在工作中安装。您还看到其他可行的替代方案吗?
  • 使用 webshot2 是一种替代方法
【解决方案2】:

gridExtra 包中的tableGrob 也可以工作

library(tidyverse)
library(grid)
library(gridExtra)

mydf <- tibble(a = c(1,2,3,4,5,4),
               b = c(4,4,4,3,3,3))

p1 <- mydf %>% ggplot(aes(x = a, y = b, color = as.factor(b))) + geom_point()

mytheme <- gridExtra::ttheme_default(
  core = list(padding = unit(c(2.5, 2.5), "mm")))
tbl <- tableGrob(mydf, theme = mytheme, rows = NULL)

grid.arrange(p1,
             tbl,
             nrow = 2,
             as.table = TRUE,
             heights = c(4, 1))

reprex package (v0.3.0) 于 2020 年 2 月 21 日创建

【讨论】:

    【解决方案3】:

    有以下两种方法

    library(tidyverse)
    library(ggpmisc)
    
    mydf <- tibble(a = c(1,2,3,4,5,4),
                   b = c(4,4,4,3,3,3))
    
    p1 <- mydf %>% ggplot(aes(x = a, y = b, color = as.factor(b))) + geom_point()
    p1 + annotate(geom = "table", x = 4.5, y = 3.5, label = list(mydf), 
               vjust = 1, hjust = 0)
    

    p1 + geom_table_npc(data = mydf, label = list(mydf),npcx = 0.05, npcy = 0.90, hjust = 0, vjust = 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多