首页 文章

如何重新排序geoms的重叠顺序,但在ggplot中保持传奇顺序不变

提问于
浏览
9

我知道我可以通过改变分组因子的 levels 来切换线绘制顺序(即,哪条线被绘制为第1,第2,第3 ......) . 但是,这样做也会切换ggplot图例的顺序 .

How do I change the plotting order but retain the original legend order?


Example

鉴于以下data.frame:

dat <- data.frame(id = rep(factor(letters[1:3]),3), y = c(1:3,3,2,1,1,3,1), x = rep(1:3,each = 3))

我可以通过更改 id 因子的 levels 来切换线绘图顺序:

  • 例如,通过使用 dat$id = relevel(dat$id, 'c') 重新排序级别 .

使用以下 ggplot 代码原始和 relevel 'ed数据:

library(ggplot2)

#Create coloring objects to kep color consistent:
  cols <- rep(1:3,3)
    names(cols) <- letters[1:3]

#Create line graph:
  ggplot(dat,aes(x=x,y=y,color=id)) + geom_line(size = 2) + 
    scale_colour_manual('id',values=cols)  ##set custom static coloring

产生以下2个图:

enter image description here

左:因子id |的原始级别顺序右:使用relevel

请注意,这些行已成功重新排序:行 c 从最后打印(因此在顶部)到最先打印(因此在底部) .

但是,传说也改变了秩序!

How do I retain the legend order from the left graph but modify the line printing order to match that of the right graph?

1 回答

  • 1

    你可能现在已经找到了解决方案 . 刚刚看到这个问题仍然是“未答复”,这里有一个建议,基于@Hendrik的评论 - 这非常有帮助,但不是整个解决方案(他的代码给出了你的情节2)

    dat$id2 = relevel(dat$id, 'c') # just create a dummy column with the releveled factors
    
    ggplot(dat) + 
      geom_line(aes(x = x, y = y, color = id2), size = 2) + 
    # use your dummy column for the line order
      scale_colour_manual('id',values = cols, breaks = levels(dat$id))  
    # use @Hendriks break suggestion
    

    enter image description here

相关问题