Reputation: 1077
I've created a facetted line chart comparing 3 different results between 2 groups over a time period. I want to be able to adjust the data labels on one of the groups (i.e. have the labels for one group appear above the data point, and labels for the second group appear below the data point).
Here is my code:
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")
)
Any help would be appreciated.
Upvotes: 3
Views: 4020
Reputation: 98439
You could use ifelse()
function inside the aes()
of geom_text()
to set different positions of y for each Group
- for one group 5 values higher and for other 5 values lower.
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))
Upvotes: 3