更改ggplot中行的重叠顺序

Sim*_*mon 9 r ggplot2

假设我有这个情节:

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)
Run Code Online (Sandbox Code Playgroud)

输出图片

如何更改绘图顺序,以便将红线绘制在其他两个上方?

因此背景是我有非常相似的线条,并希望在前景中看到特定的线条.

我想ggplot中堆叠条的答案顺序就行了.它使颜色列成为因子并改变它们的顺序,但我更愿意直接在ggplot调用的行中更改它.

我也尝试用scale_color_discrete(breaks=c("r", "g", "b")))更改图例顺序,但这也不会影响绘图顺序.

tho*_*hal 8

所以实际上最后一级col是最重要的.因此,您需要更改因子的顺序并反转颜色,因为红色会自动映射到第一级(使用标准颜色来说明问题):

pl_data$col <- factor(pl_data$col, c("r", "g", "b"))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
    geom_line(size = 3) + 
    scale_color_manual(values = c(r = "blue", g = "green", b = "red"))

## with standard colors of ggplot2, function taken from:
## http://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette

ggplotColours <- function(n = 6, h = c(0, 360) + 15) {
  if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
  hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
}
pal <- setNames(ggplotColours(3), c("b", "g", "r"))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
    geom_line(size = 3) + 
    scale_color_manual(values = pal, breaks = c("b", "g", "r"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述