在ggplot中调整数据标签

时间:2013-10-10 15:53:26

标签: r ggplot2

我创建了一个刻面线图,比较了一段时间内两组之间的3种不同结果。我希望能够调整其中一个组的数据标签(即,一组的标签显示在数据点上方,第二组的标签显示在数据点下方)。

这是我的代码:

Year <- c("Y1", "Y2","Y3", "Y1", "Y2","Y3", "Y1", "Y2","Y3", "Y1", "Y2","Y3","Y1", "Y2","Y3",
           "Y1","Y2","Y3")
Group <- c("Group A", "Group A", "Group A", "Group A", "Group A", "Group A", "Group A", "Group A", "Group A",
           "Group B", "Group B", "Group B", "Group B","Group B", "Group B", "Group B", "Group B", "Group B" )
Test <- c("Test 1", "Test 1", "Test 1", "Test 2", "Test 2", "Test 2", "Test 3", "Test 3", "Test 3",
          "Test 1", "Test 1", "Test 1","Test 2", "Test 2", "Test 2","Test 3", "Test 3", "Test 3")
Score <- c(68,70,73,61,62,65,61,62,65,
           75,74,76,74,74,77,70,71,69)
df <- data.frame (Year, Group, Test, Score)

library(ggplot2)

ggplot (df, aes (x=Year, y=Score, group=Group)) + geom_line(aes(group=Group), size=1.5) + facet_grid(.~ Test)
ggplot(df, aes(x=Year, y=Score, colour=Group)) + geom_line(aes(group=Group), size=1.5) +
  facet_grid(.~ Test) + 
  geom_point(size=4, shape=21) +
  geom_text(aes(label = Score, vjust=-1))+
  scale_y_continuous(limits = c(0,100), breaks=seq(0,100,20)) +
  ylab("Percentage of Students") + xlab ("Year") +               
  labs(title = "Chart Title") +
  theme(strip.text.x = element_text(size = 15, colour="black", angle = 0),
        strip.background = element_rect(colour="white", fill="white")
        )

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您可以在ifelse()的{​​{1}}内使用aes()函数为每个geom_text()设置不同的y位置 - 对于一组5值更高以及其他5个值低。

Group

enter image description here