Elyakim
Elyakim

Reputation: 521

Combining a table and a plot: kableExtra table not converting properly to grid graphic

I'm trying to combine a table and a plot into one image using R, with the aim to align the table and image vertically.

As I understand tableGrob() should be able to convert a kableExtra object into something usable for cowplot::plot_grid().

Unfortunately I see the underlying HTML code for the kableExtra table instead of the table itself. Before using tableGrob I can a well-formatted table in RStudio.

Should I use an alternative to tableGrob? What other options are possible to align a table and plot neatly using R?

Thanks

EDIT: I tried flextable::gen_grob() instead, which works better for now.

Below also an example of the table: enter image description here

libraries <- c("tidyverse","haven",'gridExtra','kableExtra',"gt","qwraps2","gtsummary","nlme","emmeans",'ggprism', 'cowplot', "patchwork")
lapply(libraries, require, character.only = TRUE)
        
### load data
df <- read.csv('image_data.csv')

### create plot 
custom_colors = c('#abe7f9','#1d99c9','#fee391','#fec44f','#fe9929','#d7b5d8',
                          '#bae4b3','#74c476')
plot_1 <- df %>% 
          ggplot(aes(x=trial, y=outcome, fill= treatment)) + 
          geom_col(position = "identity", alpha = 1, color='black', width = 0.6) +
          labs(
            x = "Trial",
            y = "Mean change in blood pressure compared to control group (%)",
            fill = "Treatment") +
          scale_x_discrete() + 
          coord_cartesian(ylim=c(-70,10),expand = T) +
          scale_fill_manual(values = custom_colors) + 
          theme_prism(base_size = 21) 

### load header table
df_table <- read.csv('data_table.csv')
        
header_table <- kable(df_table, escape = F) 
        
### combine table and plot
figure = cowplot::plot_grid(tableGrob(header_table), plot_1, 
                                    ncol=1, align = "v", rel_heights = c(1,4), label_size = 22)

Plot output currently

Upvotes: 0

Views: 96

Answers (0)

Related Questions