更改ggplot中行的重叠顺序

时间:2017-05-04 13:35:33

标签: 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)

pd.read_csv

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

因此背景是我的情节非常相似 线条,并希望在前台看到特定的线条。

我认为这个答案Output picture的某些内容可行。它使颜色列成为因素并改变它们的顺序,但我宁愿改变 这直接在ggplot调用的一行中。

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

2 个答案:

答案 0 :(得分:7)

所以实际上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"))

enter image description here

答案 1 :(得分:2)

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)