r - 如何在 ggplot 中为多个变量和绘图创建唯一的图例/颜色标签
问题描述
我正在尝试创建一个多图页面,以便随着时间的推移比较疾病变量和患者状态(即已故或康复)中的多个变量。
这是我的代码
p1 <- g + geom_smooth(data = sofa_vivo_vs_mortos, aes(x = days, y = sofa_score, color = outcome, group = outcome)) + scale_x_continuous(breaks = sofa_vivo_vs_mortos$days)
+ geom_smooth(data = sofa_vivo_vs_mortos, aes(x = days, y = resp_score, color = outcome, group = outcome)) + values = c("blue", "red")) + labs(x="Days after admission")
p2 <- g + geom_smooth(data = sofa_vivo_vs_mortos, aes(x = days, y = sofa_score, color = outcome, group = outcome)) + scale_x_continuous(breaks = sofa_vivo_vs_mortos$days)
+ geom_smooth(data = sofa_vivo_vs_mortos, aes(x = days, y = coag_score, color = outcome, group = outcome)) + labs(x="Days after admission")
ggarrange(p1, p2, labels = c("A", "B"), ncol = 2)
产生以下情节:
由于无法区分图中的哪个变量,我希望我的代码产生:
1-整个页面的独特图例位置
2-每个变量的颜色图例不仅基于它的分组变量(在我的代码中,outcome
变量),而且还基于变量本身的名称(即一种颜色+图例用于sofa_score
变量其中outcome = deceased
和另一种用于sofa_score
其中outcome = recovered
,组合在与分析中的第二个变量相同的图中(即resp_score
具有相同outcome
分层的变量)
编辑样本数据:
df2 <- data.frame(ID = seq(1,32, by=1), sofa_score = sample(1:8, 8, replace = TRUE), resp_score = sample(1:8, 8, replace = TRUE),
outcome = c('deceased', 'recovered'),
days = sample(1:20, 32, replace = TRUE), coag_score = sample(1:8, 8, replace = TRUE))
解决方案
我通常发现拼凑包非常适合情节组合,包括从多个情节中收集图例。一个例子:
library(ggplot2)
library(patchwork)
set.seed(42)
df2 <- data.frame(
ID = seq(1,32, by=1),
sofa_score = sample(1:8, 8, replace = TRUE),
resp_score = sample(1:8, 8, replace = TRUE),
outcome = c('deceased', 'recovered'),
days = sample(1:20, 32, replace = TRUE),
coag_score = sample(1:8, 8, replace = TRUE)
)
p1 <- ggplot(df2, aes(days)) +
geom_smooth(aes(y = coag_score, colour = outcome, group = outcome)) +
scale_colour_manual(
values = c("tomato", "dodgerblue"),
name = "Coag Score"
)
p2 <- ggplot(df2, aes(days)) +
geom_smooth(aes(y = resp_score, colour = outcome, group = outcome)) +
scale_colour_manual(
values = c("limegreen", "orchid"),
name = "Resp Score"
)
p1 + p2 + plot_layout(guides = "collect")
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
由reprex 包(v0.3.0)于 2021-03-17 创建
推荐阅读
- angular - 在Angular中添加新记录时如何使用事件发射器自动刷新列表组件?
- javascript - 来自窗口的电子访问请求/响应正文和标头
- android - 如何在 Gradle 构建中为 versionCode/versionName 提供属性
- python - 如何在python中将txt文件转换为pickle文件?
- javascript - 如何满足与匹配 MediaQuery && 包含 classList 的语句
- php - Wodpress 查询参数 (?p) 如果不是数字则重定向
- java - 如何在 Java 中使用正则表达式来操作字符串
- oracle - 是否可以在同一服务器 ind odp.net 中的两个应用程序之间共享连接池
- swift - 如何从错误响应中访问值
- javascript - 在 macOS 上使用 VoiceOver 时将焦点锁定在可滚动元素内的锚标记上