Fig1b [1]
library(ggplot2) # 需提前安装install.packages("ggplot2")
set.seed(1)
data <- data.frame(
types = c(rep("BA.1", 111), rep("BA.2", 195), rep("Alpha", 18), rep("Delta", 117)),
groups = c(rep("Persistent infection", 97), rep("Reinfection", 14),
rep("Persistent infection", 167), rep("Reinfection", 28),
rep("Persistent infection", 11), rep("Reinfection", 7),
rep("Persistent infection", 106), rep("Reinfection", 11)),
days = c(sample(26:180, 97, replace = T), # BA.1
sample(26:75, 14, replace = T),
sample(26:140, 167, replace = T), # BA.2
sample(30:125, 27, replace = T), 200,
sample(26:190, 11, replace = T), # Alpha
sample(26:165, 7, replace = T),
sample(26:130, 106, replace = T), # Delta
sample(26:150, 11, replace = T)))
summary(data)
ggplot(data, aes(x = types, y = days)) +
geom_point(aes(color = groups),
size = 1,
position = position_jitterdodge(dodge.width = 0.9,
seed = 2,
jitter.width = 0.3,
jitter.height = 0.1)) +
scale_y_continuous(breaks = c(50, 100, 150, 200),
limits = c(18, 200)) +
scale_x_discrete(limits = c("Alpha", "Delta", "BA.1", "BA.2")) +
scale_color_manual(values = c("mediumaquamarine", "plum3"),
limits = c("Reinfection", "Persistent infection")) +
geom_hline(yintercept = 26, color = "grey") +
geom_hline(yintercept = 56, color = "grey") +
coord_flip() +
theme_classic(base_size = 14) +
theme(legend.position = "top",
legend.justification = "right",
axis.text = element_text(color = "black")) +
guides(colour = guide_legend(override.aes = list(size = 3))) +
labs(x = "",
y = "Time between the earliest and latest samples (days)",
color = "") +
annotate("text", x = 4.2, y = 18, label = "28", size = 4) +
annotate("text", x = 3.8, y = 18, label = "167", size = 4) +
annotate("text", x = 3.2, y = 18, label = "14", size = 4) +
annotate("text", x = 2.8, y = 18, label = "97", size = 4) +
annotate("text", x = 2.2, y = 18, label = "11", size = 4) +
annotate("text", x = 1.8, y = 18, label = "106", size = 4) +
annotate("text", x = 1.2, y = 18, label = "7", size = 4) +
annotate("text", x = 0.8, y = 18, label = "11", size = 4)
类似原论文中的图就轻松get!
上述代码中,函数 geom_point() 添加一个几何图层,在此例中是点图。position = position_jitterdodge() 处理重叠的点:dodge.width = 0.9 控制两个亚组分别往两侧偏移;seed = 2 让随机可重复;jitter.width = 0.3 和 jitter.height = 0.1 给点添加额外的随机抖动。
[1] https://www.nature.com/articles/s41586-024-07029-4/figures/1