r - 如何在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)
解决方案
我建议使用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)
输出:
推荐阅读
- c# - 通用 C# 函数问题创建
- google-bigquery - 从 Google 公共数据集中提取特定年份的数据 - chicago_taxi_trips
- android - 如何在 Android 中使用摄像头读取和计算人体血压?
- javascript - 下载zip并保存解压
- python - 如何避免使用 Selenium 在网络抓取中出现文本图像验证码
- assembly - 汇编语言堆栈帧访问冲突读取位置问题
- angular - aria-label 属性不起作用 ngb-tabset
- r - 配置 Docker 容器和 R 以允许从容器内部进行 API 查询?
- amazon-web-services - 如何在 Cloudformation 中按用户名隔离事件
- gitlab-ci - 如何检查使用 MkDocs 构建静态站点的 Gitlab CI 作业中的死链接?