Home > database >  can not left align with cowplot package
can not left align with cowplot package

Time:06-09

In the current plot, p2 is now centered. I want p2 to be aligned with p1 on the left. I tried some of the parameters in plot_grid, but the image didn't change at all.

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)

# orginal plot
cowplot::plot_grid(p1, p2, nrow = 2, ncol = 1, rel_heights = c(1, 1) )

# left align plot (Nothing changed with orginal plot)
cowplot::plot_grid(p1, p2, nrow = 2, ncol = 1, rel_heights = c(1, 1), align = 'v' )
cowplot::plot_grid(p1, p2, nrow = 2, ncol = 1, rel_heights = c(1, 1), axis = 'l' )
cowplot::plot_grid(p1, p2, nrow = 2, ncol = 1, rel_heights = c(1, 1), axis = 'tblr' )

CodePudding user response:

The problem is that the raster object is placed bang in the middle of your plot. Check ggplot() annotation_custom(rasterGrob(ft_raster)) without theme_void. You can play around with the coordinates for your raster (by the way, the Infs are defaults...

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()  
# play around with this !
  annotation_custom(rasterGrob(ft_raster), xmax = 0.2)

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

Created on 2022-06-08 by the reprex package (v2.0.1)

  • Related