Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

r - how to add a table to a ggplot?

I am trying to combine (in a single chart) a regular ggplot chart with a table obtained with flextable.

Consider the following example:

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 looks like

enter image description here

but unfortunately I cannot combine it with p1

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

What can we do? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use fonction flextable::as_raster to get a raster from a flextable and then add with annotation_custom to an empty ggplot object.

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

Documentation is here: https://davidgohel.github.io/flextable/articles/offcran/images.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...