繁体   English   中英

R ggplot:结合长数据集中的条形图和折线图

[英]R ggplot: Combine a barplot and a line chart from a long dataset

我有一个广泛的数据集,记录了 10 个受试者的血糖值。

library(dplyr) 

df_wide = data.frame(
  ID = seq(1, 10),
  gender = sample(0:1, 10, replace = T),
  glucose_0 = sample(100:125, 10, replace = T),
  glucose_60 = sample(180:200, 10, replace = T),
  glucose_120 = sample(130:160, 10, replace = T),
  glucose_180 = sample(100:125, 10, replace = T)
) 

然后我使用 collect 将其转换为一个长数据gather

df_long = df_wide %>% 
  gather("glucose_0", "glucose_60", "glucose_120", "glucose_180", key = Time, value = glucose) %>% 
  arrange(ID)

为了显示葡萄糖值如何从 0 分钟变为 180 分钟,我制作了以下折线图:

df_long %>% 
  ggplot(aes(x = Time, y = glucose, group = ID)) + 
  geom_line(aes(linetype = as.factor(gender))) +
  geom_point() +
  theme_classic() +
  scale_x_discrete(limits = c("glucose_0", "glucose_60", "glucose_120", "glucose_180"),
                   labels = c("0", "60", "120", "180")) +
  theme(legend.position = "bottom") +
  labs(
    x = "Time",
    y = "Glucose",
    fill = "Gender"
  ) 

最后,为了显示每个时间点的葡萄糖,我还做了一个条形图:

df_long %>% 
  ggplot(aes(x = Time, y = glucose, fill = as.factor(gender))) + 
  geom_bar(stat = 'identity', position = position_dodge()) +
  theme_classic() +
  scale_x_discrete(limits = c("glucose_0", "glucose_60", "glucose_120", "glucose_180")) 

我的问题是:如何将折线图和条形图组合成一个看起来像这样的图形? 目标

您可以简单地从折线图中添加geom_line()geom_point()图层,如下所示? 我不清楚您希望如何看到这种组合。

df_long %>% 
  ggplot(aes(x = Time, y = glucose, fill = as.factor(gender))) + 
  geom_bar(stat = 'identity', position = position_dodge()) +
  geom_line(aes(linetype=as.factor(gender), group=ID)) +
  geom_point() + 
  theme_classic() +
  scale_x_discrete(limits = c("glucose_0", "glucose_60", "glucose_120", "glucose_180")) 

结果图

您是否正在寻找这样的解决方案?

library(tidyverse)

df_wide %>% 
  pivot_longer(
    starts_with("glucose")
  ) %>% 
  mutate(gender = fct_inorder(factor(gender))) %>% 
  arrange(ID) %>% 
  ggplot(aes(x = name, y = value)) + 
  geom_line(aes(linetype = gender, group = gender)) +
  geom_point() +
  geom_col(aes(fill = gender), width = 0.5, position = position_dodge(0.7), alpha=0.7)+
  theme_classic() +
  scale_x_discrete(limits = c("glucose_0", "glucose_60", "glucose_120", "glucose_180"),
                   labels = c("0", "60", "120", "180")) +
  theme(legend.position = "bottom") +
  labs(
    x = "Time",
    y = "Glucose",
    fill = "Gender"
  ) 

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM