R 调整ggplot中的数据标签
我创建了一个分面折线图,比较了一段时间内两组之间的3个不同结果。我希望能够调整其中一个组上的数据标签(即,一个组的标签显示在数据点上方,第二个组的标签显示在数据点下方) 这是我的密码:R 调整ggplot中的数据标签,r,ggplot2,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
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")
)
Year您可以在geom_text()
的aes()
中使用ifelse()
函数,为每个组设置不同的y位置
——一组的5个值较高,另一组的5个值较低
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))