如果我有一个由 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 轴位于对照组和疾病组之间的中间,而不是虚线。
希望能帮到你。非常感谢!
你不能让一个轴穿过 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')