1

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)

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

@r2evans For sure your answer must be 100/100 more elaborated :)
Thanks, is there a way to format the table 1. in theme-bw() and 2. remove no. from leftside.
and how to position it, lets say I want to place the table below the figure. I thought of creating another plot object for table and then use cowplot to arrange as desired
@SiD I have added an update, let me know if that works for you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.