3

我创建了一个多面折线图,比较了一段时间内两组之间的 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")
        )

任何帮助,将不胜感激。

4

1 回答 1

3

您可以使用of 中的ifelse()函数为每个设置不同的 y 位置- 一组高 5 个值,其他 5 个值低。aes()geom_text()Group

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(y=ifelse(Group=="Group B",Score+5,Score-5),label = Score))+
  scale_y_continuous(limits = c(0,100), breaks=seq(0,100,20))

在此处输入图像描述

于 2013-10-10T16:02:26.127 回答