首页 > 解决方案 > 如何在ggplot网格中添加表格

问题描述

我想在最终图中的散点图旁边汇总表。汇总表应位于绘图旁边。这是示例代码。

我们怎么能做到这一点?

谢谢

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)

标签: rggplot2

解决方案


我建议使用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)

输出:

在此处输入图像描述

您可以使用gridExtra::tableGrob()

试试这个颜色和顺序:

# 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)

输出:

在此处输入图像描述


推荐阅读