R 在同一张图上绘制 2 条带置信区间的线

问题描述 投票:0回答:1

我想在同一张图上用优势比和置信区间画两条线。 X 轴是年龄组,y 轴是优势比。有两组:病例和对照

这是我到目前为止尝试过的

age_group <- c("18-30", "30-45", "45-60", "60-75", "75-90", "90+")

df_hosp_adm_can <- data.frame(
  age_group = 1:length(age_group),
  Number_of_hospitalisation = c(3.1, 11.9, 9.6, 9, 93, 8.9),
  range_days = c(4.3, 19.6, 29.5, 24.3, 25.3, 25.2)
)

df_hosp_adm_non_can <- data.frame(
  age_group = 1:length(age_group),
  Number_of_hospitalisation =
    c(3.1, 3.2, 2.5, 3.3, 4.8, 5.0),
  range_days =
    c(5.8, 10.9, 14.6, 16.1, 21.2, 14.3)
)

hosp_adm <- df_hosp_adm_can %>%
  mutate(Group = "Case") %>%
  bind_rows(df_hosp_adm_non_can %>% mutate(Group = "Control")) %>%
  mutate(Group = Group %>% fct_inorder())

hosp_adm %>% ggplot(aes(age_group, Number_of_hospitalisation,
  fill = Group, color = Group
)) +
  geom_line() +
  geom_ribbon(aes(
    ymin = Number_of_hospitalisation - range_days,
    ymax = Number_of_hospitalisation + range_days, color = NULL
  ), alpha = 0.2)

这将生成此图,其中 1、2、3、4、5、6 作为 x 轴而不是年龄组。当我尝试将两个数据帧的代码更改为此时:

df_hosp_adm_non_can <- data.frame(age_group), 
                              Number_of_hospitalisation = 
       c(3.1,3.2,2.5,3.3,4.8,5.0), 
                              range_days = 
      c(5.8,10.9,14.6,16.1,21.2,14.3)
)

我收到错误消息“aes is missing”。我做错了什么

r ggplot2 confidence-interval linegraph
1个回答
0
投票

使用

data.frame(age_group, ...)
是要走的路。但在那种情况下,您必须添加
group
美学,即添加
group = Group
作为
age_group
是离散变量或分类变量(也许这就是您所说的“缺少 aes”的意思?):

library(tidyverse)

age_group <- c("18-30", "30-45", "45-60", "60-75", "75-90", "90+")

df_hosp_adm_can <- data.frame(
  age_group,
  Number_of_hospitalisation = c(3.1, 11.9, 9.6, 9, 93, 8.9),
  range_days = c(4.3, 19.6, 29.5, 24.3, 25.3, 25.2)
)

df_hosp_adm_non_can <- data.frame(
  age_group,
  Number_of_hospitalisation = c(3.1, 3.2, 2.5, 3.3, 4.8, 5.0),
  range_days = c(5.8, 10.9, 14.6, 16.1, 21.2, 14.3)
)

hosp_adm <- list(
  Case = df_hosp_adm_can,
  Control = df_hosp_adm_non_can
) |>
  bind_rows(.id = "Group") |>
  mutate(Group = fct_inorder(Group))

hosp_adm %>%
  ggplot(aes(age_group, Number_of_hospitalisation,
    fill = Group, color = Group, group = Group
  )) +
  geom_line() +
  geom_ribbon(aes(
    ymin = Number_of_hospitalisation - range_days,
    ymax = Number_of_hospitalisation + range_days, color = NULL
  ), alpha = 0.2)

© www.soinside.com 2019 - 2024. All rights reserved.