SiH
SiH

Reputation: 1546

how to add table in ggplot grid

I want to summary table next to the scatterplot in the final figure. The summary table should come next to the plot. Here is the sample code.

How can we do that?

Thanks

library(tidyverse)
library(cowplot)

# data
x <- runif(10000)
y <- runif(10000)
z <- c(rep(0, 5000), rep(1, 5000))

tbl <- tibble(x, y, z)

# plot
scatterplot <- ggplot(tbl,
                      aes(x = x,
                          y = y)) + 
  geom_point(alpha = 0.7,
             size = 2) +
  facet_grid(. ~ z) + 
  theme_bw() +  
  theme(aspect.ratio = 1) +
  ggtitle("Scatter plot")

# add summary table
summary_tbl <- tbl %>%
  group_by(z) %>%
  summarise(count = n(),
            x_mean = mean(x),
            y_mean = mean(y))


# TASK
# to create a final plot with scatterplot and summary table in single row grid
plot_grid(scatterplot, summary_tbl,
          nol = 2)

Upvotes: 1

Views: 956

Answers (1)

Duck
Duck

Reputation: 39595

I would suggest using patchwork:

library(tidyverse)
library(cowplot)
library(patchwork)
# data
x <- runif(10000)
y <- runif(10000)
z <- c(rep(0, 5000), rep(1, 5000))

tbl <- tibble(x, y, z)

# plot
scatterplot <- ggplot(tbl,
                      aes(x = x,
                          y = y)) + 
  geom_point(alpha = 0.7,
             size = 2) +
  facet_grid(. ~ z) + 
  theme_bw() +  
  theme(aspect.ratio = 1) +
  ggtitle("Scatter plot")

# add summary table
summary_tbl <- tbl %>%
  group_by(z) %>%
  summarise(count = n(),
            x_mean = mean(x),
            y_mean = mean(y))


# TASK
G <- scatterplot + gridExtra::tableGrob(summary_tbl)

Output:

enter image description here

You can wrap your table using gridExtra::tableGrob()

Try this for colors and order:

# TASK 2
my_table_theme <- gridExtra::ttheme_default(core=list(bg_params = list(fill = 'white', col=NA)))
#Plot
G <- scatterplot / gridExtra::tableGrob(summary_tbl,
                                        rows = NULL,theme=my_table_theme)

Output:

enter image description here

Upvotes: 2

Related Questions