如何使用图例在ggplot2中创建分段图?

HNSKD

我有如下数据: 在此处输入图片说明

我想创建一个分段图(例如前图和后图,包括在t = 10处的垂直线,以指示变化。t指的是经过的时间,x前执行指0,后执行指1实施,count_visit_triage\\d是我想在y轴上绘制的计数数据。

这是我的R代码。我将多个拼凑geom_smooth成一个数字,每种颜色代表的值triage1triage2等等。因此,我无法获得图例。我的问题是(1)如何简化此代码,以便图例可以包含在图中?

ggplot(df, aes(x = t, y = count_visit_triage1)) +
  geom_smooth(data = subset(df, x == 0), aes(x = t, y = count_visit_triage1), colour = "blue", se = F) +
  geom_smooth(data = subset(df, x == 1), aes(x = t, y = count_visit_triage1), colour = "blue", se = F) +
  geom_smooth(data = subset(df, x == 0), aes(x = t, y = count_visit_triage2), colour = "orange", se = F) +
  geom_smooth(data = subset(df, x == 1), aes(x = t, y = count_visit_triage2), colour = "orange", se = F) +
  geom_smooth(data = subset(df, x == 0), aes(x = t, y = count_visit_triage3), colour = "green", se = F) +
  geom_smooth(data = subset(df, x == 1), aes(x = t, y = count_visit_triage3), colour = "green", se = F) +
  geom_smooth(data = subset(df, x == 0), aes(x = t, y = count_visit_triage4), colour = "red", se = F) +
  geom_smooth(data = subset(df, x == 1), aes(x = t, y = count_visit_triage4), colour = "red", se = F) +
  geom_vline(xintercept = 10, linetype = "dashed") + 
  theme_bw()

在此处输入图片说明

资料

df <- structure(list(t = 1:20, x = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), count_visit_triage1 = c(42L, 
55L, 61L, 52L, 58L, 38L, 47L, 46L, 66L, 44L, 24L, 17L, 40L, 25L, 
18L, 23L, 34L, 35L, 22L, 23L), count_visit_triage2 = c(175L, 
241L, 196L, 213L, 189L, 163L, 181L, 166L, 229L, 224L, 153L, 139L, 
125L, 145L, 134L, 115L, 152L, 153L, 136L, 154L), count_visit_triage3 = c(120L, 
114L, 106L, 88L, 108L, 103L, 103L, 93L, 80L, 81L, 88L, 94L, 94L, 
77L, 91L, 100L, 93L, 70L, 79L, 77L), count_visit_triage4 = c(3L, 
0L, 0L, 1L, 2L, 2L, 0L, 4L, 4L, 2L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 
0L, 1L, 2L)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", 
"data.frame"))
保罗

重塑数据,然后指定colgroup

library(tidyverse)

df %>%
  pivot_longer(starts_with("count_")) %>%
  ggplot(aes(t, value, col = name, group = paste(x, name))) +
    geom_smooth(se = FALSE) +
    geom_vline(xintercept = 10, linetype = "dashed") + 
    theme_bw()

情节

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章