首页 > 解决方案 > 如何在 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分层的变量)

类似的期望结果: 请注意每个图中有 4 行,每个变量 2 行,变量内的每个结果 1

编辑样本数据:

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

标签: rggplot2plotdata-visualization

解决方案


我通常发现拼凑包非常适合情节组合,包括从多个情节中收集图例。一个例子:

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 创建


推荐阅读