繁体   English   中英

R GGplot - 在循环中的 X 轴上添加额外的刻度线文本

[英]R GGplot - Add additional tick-mark text on X axis in a loop

我有一个 df 看起来像这样:

students    test_number grade   date    Annotation
Jack    1   81.50107086 1/12/20 Math
Jack    2   95.44902345 1/13/20 Math
Jack    3   97.06091615 1/14/20 Math
Jack    4   95.27667508 1/15/20 Math
Jill    1   92.49229    2/15/20 Math
Jill    2   87.8457308  2/16/20 Math
Jill    3   85.4860858  2/17/20 Math
Jill    4   86.69897954 2/18/20 Math
Jake    1   88.35111817 1/11/20 Math
Jake    2   93.78062799 1/12/20 Math
Jake    3   95.69871618 1/13/20 Math
Jake    4   85.58356608 1/14/20 Math
Phill   1   93.46926154 1/12/20 Math
Phill   2   96.20396083 1/13/20 Math
Phill   3   87.70421535 1/14/20 Math
Phill   4   81.49549922 1/15/20 Math

我正在遍历每个学生,为每个测试制作一个折线图(示例数据只有“数学”,但在同一日期有 3 个测试),x 轴为测试编号,如下所示:

plot_list = list()
for (var in unique(all_students$students)) {
  p = ggplot(all_students[all_students$students==var,], aes(x=test_number, y=grade, group=Annotation)) +
    geom_line()+           
    geom_point() +
    ggtitle(var) +
    scale_shape(guide = FALSE) +
    xlab("Test Date + Number")
  plot_list[[var]] = p
}
pdf("all_students.pdf")
for (var in unique(all_students$students)) {
  print(plot_list[[var]])
}
dev.off()

但我希望 X 轴包含日期和测试编号。 现在它只包括测试编号。

我试过添加:

geom_text(aes(x=test_number, label=date))

但这会在绘图上而不是在 X 轴上添加日期。 还试过:

    scale_x_discrete(labels= all_students$date)

但这将第一个观察到的日期添加为所有学生的 X 轴刻度线(即所有图的日期与 X 轴相同)

谢谢!

您可以尝试test_numberdate连接。

all_students <- all_students %>%
  rowwise %>%
  mutate(idx = paste0(c(date, test_number), collapse = " - "))
for (var in unique(all_students$students)) {
  p = ggplot(all_students[all_students$students==var,], aes(x=idx, y=grade, group=Annotation)) +
    geom_line()+           
    geom_point() +
    ggtitle(var) +
    scale_shape(guide = FALSE) +
    xlab("Test Date + Number")
  plot_list[[var]] = p
}
plot_list$Jack

在此处输入图片说明

另外,如果您想在不同的行中显示日期和测试编号,

all_students <- all_students %>%
  rowwise %>%
  mutate(idx = paste0(c(date, test_number), collapse = "\n"))

在此处输入图片说明

暂无
暂无

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

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