在R Tidyverse中创建时间轴

qcbq4gxm  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(91)

如果我有一个由ID(1到20)、年龄、性别和疾病/对照组组成的数据集(见下文),那么我如何基于从0到99的“年龄”创建一个时间轴,其中我将来自“疾病”组的所有样本都在时间线之上,而所有“对照”个体都在时间线之下?此外,如果例如两个相同年龄的病人我会把他们叠在一起吗?最好在两者之间有一个时间轴(x轴),这样它就能成为一个实际的时间线,而不仅仅是我现在所在的虚线?请参阅下面的数据和代码,我得到了:

Age = c(10, 10, 11, 15, 50, 20, 25, 24, 24, 10, 12, 25, 99, 80, 99, 20, 58, 76, 19, 19), 
   disease = c("disease", "disease", "control", "control", "disease", "control", "disease", "control", "disease", "control", "control", "disease", "control", "control", "disease", "disease", "control", "disease", "control", "control"),
   gender = sample(c("M", "F"), 20, replace = TRUE))

剧情:

ggplot(aes(x = Age, y = disease, color = gender)) + 
      geom_text(aes(label = gender), check_overlap = FALSE) +
      geom_hline(yintercept = 1.5, linetype = "dashed", color = "black") +
      scale_y_discrete(limits = c("disease", "control")) + 
      labs(x = "Age", y = "Disease") +
      theme_LasseVoss1()

它返回以下内容(请参见附件):

问题是:
1)我希望时间轴/X轴位于对照组和疾病组之间的中间,而不是虚线。
1.如果有两个年龄相同(或年龄非常接近)的人来自同一组,他们应该堆叠在一起。
希望你能帮上忙。非常感谢!

oxcyiej7

oxcyiej71#

在ggplot中,你不能让一个轴穿过图的中间,所以你必须自己滚动一个。您可以通过添加文本和线条图层或通过拼接图来完成此操作。我觉得第一个版本比较容易。
要有条件地隐藏可能会冲突的标签,请使用ggrepel包中的geom_text_repel。设置direction = "y"以确保匀光仅垂直发生。

ggplot(data, aes(x = Age, y = disease)) + 
  ggrepel::geom_text_repel(aes(label = gender, color = gender),
                           direction = 'y', segment.color = 'transparent') +
  geom_hline(yintercept = 1.5, color = "black") +
  geom_text(aes(label = after_stat(x)), vjust = 1,
            data = data.frame(Age = 1:4 * 25, disease = 1.45)) +
  geom_linerange(aes(ymin = 1.48, ymax = 1.5),
                 data = data.frame(Age = 1:4 * 25, disease = 1.45)) +
  annotate('text', x = 57.5, y = 1.3, label = 'Age', size = 14/.pt,
           fontface = 'bold') + 
  scale_y_discrete(limits = c("disease", "control")) + 
  labs(x = "Age", y = "Disease") +
  theme_classic(base_size = 16) +
  theme(text = element_text(face = 2),
        axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        panel.border = element_rect(fill = NA, color = 'black', 
                                    linewidth = 0.8),
        axis.ticks = element_blank(),
        legend.position = 'bottom')

相关问题