我有 3 个时间点的 BMI 和 HTN 数据,其中 BMI 是连续的,HTN 是分类的。我应该通过折线图(BMI 的连续值和 HTN 的数字)之类的图形显示这 3 次 BMI 和 HTN 的变化。有没有办法在R中做到这一点?我可以在一个图中同时显示两个图吗?谢谢。
ID | BMI_1 | BMI_2 | BMI_3 | HTN_1 | HTN_2 | HTN_3 |
---|---|---|---|---|---|---|
A1 | 35 | 37 | 40 | 0 | 0 | 1 |
A2 | 29 | 32 | 35 | 0 | 1 | 1 |
A3 | 38 | 39 | 42 | 1 | 1 | 1 |
A4 | 33 | 34 | 34 | 0 | 0 | 0 |
答案 0 :(得分:1)
我们可以使用 pivot_longer
将格式重塑为“长”格式并使用 ggplot
library(dplyr)
library(tidyr)
library(ggplot2)
df1 %>%
pivot_longer(cols = -ID, names_to = c('.value', 'grp'),
names_sep = "_") %>%
mutate(grp = as.integer(grp)) %>%
ggplot() +
geom_line(aes(x = grp, y = BMI, group = ID, color = ID)) +
geom_line(aes(x = grp, y = HTN, group = ID, color = ID)) +
theme_bw()
如果我们想要两个图,可以使用facet_wrap
df1 %>%
pivot_longer(cols = -ID) %>%
separate(name, into = c('name', 'grp'), convert = TRUE) %>%
ggplot(aes(x = grp, y = value, color = ID, group = ID)) +
geom_line() +
facet_wrap(~ name) +
theme_bw()
-输出
scales
可以在 facet_wrap
...
facet_wrap(~ name, scales = 'free_y') +
...
df1 <- structure(list(ID = c("A1", "A2", "A3", "A4"), BMI_1 = c(35L,
29L, 38L, 33L), BMI_2 = c(37L, 32L, 39L, 34L), BMI_3 = c(40L,
35L, 42L, 34L), HTN_1 = c(0L, 0L, 1L, 0L), HTN_2 = c(0L, 1L,
1L, 0L), HTN_3 = c(1L, 1L, 1L, 0L)), class = "data.frame", row.names = c(NA,
-4L))
答案 1 :(得分:1)
这是您要找的吗?
library(tidyverse)
df1 %>%
summarise(across(-ID, mean)) %>%
pivot_longer(cols = everything(), names_to = c("stat", "time"), names_sep = "_") %>%
ggplot(aes(time, value, group = stat)) +
geom_line() +
facet_wrap(~stat, scales = "free_y") +
expand_limits(y = 0)
或者:
df1 %>%
summarise(across(-ID, mean)) %>%
pivot_longer(cols = everything(), names_to = c("stat", "time"), names_sep = "_") %>%
pivot_wider(names_from = stat, values_from = value) %>%
ggplot(aes(BMI, HTN, label = time)) +
geom_path() +
geom_label()