как добавить таблицу в ggplot? - PullRequest
3 голосов
/ 22 февраля 2020

Я пытаюсь объединить (на одном графике) обычный график 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 выглядит как

enter image description here

но, к сожалению, я не могу объединить это с p1

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

Что мы можем сделать? Спасибо!

Ответы [ 3 ]

5 голосов
/ 22 февраля 2020

Вы можете использовать функцию 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) )

enter image description here

Документация здесь: https://davidgohel.github.io/flextable/articles/offcran/images.html

2 голосов
/ 22 февраля 2020

tableGrob из пакета gridExtra тоже работает

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))

Создано в 2020-02-21 Представить пакет (v0.3.0)

1 голос
/ 22 февраля 2020

Существует 2 следующих способа

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)

enter image description here

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

enter image description here

...