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
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!
This R package uses ggplot2 syntax to create great tables. for plotting. The grammar of graphics allows us to add elements to plots. Tables seem to be forgotten in terms of an intuitive grammar with tidy data philosophy – Until now.
We can create a table by using as. table() function, first we create a table using matrix and then assign it to this method to get the table format. Example: In this example, we will create a matrix and assign it to a table in the R language.
%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.
The function geom_point() adds a layer of points to your plot, which creates a scatterplot. ggplot2 comes with many geom functions that each add a different type of layer to a plot.
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) )
Documentation is here: https://davidgohel.github.io/flextable/articles/offcran/images.html
tableGrob
from the gridExtra
package works too
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))
Created on 2020-02-21 by the reprex package (v0.3.0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With