Reputation: 85
I have test score data. I want ggline plot for 3 different test scores in reading over various years (3 lines). I would like this stacked over 4 different test scores in writing the same years (4 lines). Having all 7 on one plot is confusing to read. I can subset the data so it shows either reading or writing, but I can't seem to stack them over top of each other neatly.
year, ID, test, score , type
2010, 1, R1, 72.75, R
2010, 1, R2, 68.25, R
2010, 1, R3, 83.75, R
2010, 1, W1, 89.25, W
2010, 1, W2, 58.25, W
2010, 1, W3, 64.25, W
2010, 1, W4, 90.25, W
2011, 1, R1, 52.25, R
2011, 1, R2, 90.25, R
2011, 1, R3, 73.25, R
2011, 1, W1, 79.5, W
2011, 1, W2, 89.25, W
2011, 1, W3, 85.25, W
2011, 1, W4, 78.25, W
…
I have this code to produce one graph with just reading:
ggplot(subset(df,skill %in% c("R1", "R2", "R3"))) +
geom_line(aes(year, score, group=skill, colour=skill))
I have tried to do this to get both, but it obviously is incorrect:
p1 <- subset(df,skill %in% c("R1", "R2", "R3"))
p2 <- subset(df,skill %in% c("W1", "W2", "W3", "W4"))
ggplot()+ geom_line(data=p1, aes(year, score, group=skill, colour=skill)) +
geom_line(data=p2, aes(year, score, group=skill, colour=skill)) +
facet_grid(~type)
Any help would be greatly appreciated
Upvotes: 2
Views: 1109
Reputation: 3240
If you're going to facet based on type, you don't need to subset the data into p1 and p2.
ggplot(df) +
geom_line(aes(year, score, group = skill, colour = skill)) +
facet_wrap(~type)
Alternative, adding nrow =2
to stack the plots and scales = "free"
to give them independent axes.
ggplot(df) +
geom_line(aes(year, score, group = skill, colour = skill)) +
facet_wrap(~type, nrow = 2, scales = "free")
However, your comment says
This does work but it puts the graph side by side instead of stacked vertically. Is there a way to stack them one on top of the other and perhaps separate the legend so reading and writing are separate?
To address the separate legend, I would make each plot, and then combine using the package cowplot
. Other ways to do this using gridExtra
but cowplot
makes this simple.
p1 <- ggplot(subset(df,skill %in% c("R1", "R2", "R3"))) +
geom_line(aes(year, score, group = skill, colour = skill)) +
facet_wrap(~type, scales = "free")
p2 <- ggplot(subset(df,type %in% c("W"))) +
geom_line(aes(year, score, group = skill, colour = skill)) +
facet_wrap(~type, scales = "free")
cowplot::plot_grid(p1, p2, nrow = 2)
Upvotes: 1