如何将表添加到ggplot? [英] how to add a table to a ggplot?

查看:133
本文介绍了如何将表添加到ggplot?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将常规ggplot图表与通过flextable获得的表合并(在单个图表中).

I am trying to combine (in a single chart) a regular ggplot chart with a table obtained with 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

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!

推荐答案

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

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

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

这篇关于如何将表添加到ggplot?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆