'Change the overlaying order of lines in ggplot
Suppose I have this plot:
library(ggplot2)
pl_data <- data.frame(x = rep(c(1, 2), times = 3), y = c(0, 1, 1, 0, .7, .7), col = rep(c("r", "b", "g"), each = 2))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
geom_line(size = 3)
How can I change the plotting order, so that the red line is plotted above the other two?
The background therefore is that I have plots with very similar lines, and want to see specific lines in the foreground.
I suppose something along the lines of this answer order of stacked bars in ggplot would work. It makes the color column to factors and changes their order, but I would prefer to change this directly in a line of the ggplot call.
I also tried changing the legend order with scale_color_discrete(breaks=c("r", "g", "b"))),
but that does not effect the plotting order either.
Solution 1:[1]
library(ggplot2)
df <- data.frame(
x = rep(c(1, 2), times = 3),
y = c(0, 1, 1, 0, .7, .7),
col = rep(c("r", "b", "g"), each = 2))
ggplot() +
geom_line(data = df[3:4,], aes(x = x, y = y), color = 'blue', size = 3) +
geom_line(data = df[5:6,], aes(x = x, y = y), color = 'green', size = 3) +
geom_line(data = df[1:2,], aes(x = x, y = y), color = 'red', size = 3)
Solution 2:[2]
hi when you are plotting lines it is the group ID - the highest group ID goes on top
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dutchmv |
| Solution 2 | Jeremy Affolter |

