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

the*_*ist 9 r legend ggplot2

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

如何更改绘图顺序但保留原始图例顺序?


鉴于以下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))
Run Code Online (Sandbox Code Playgroud)

我可以切换线路通过改变绘图命令levels的的id因素:

  • 例如,通过使用重新排序级别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
Run Code Online (Sandbox Code Playgroud)

产生以下2个图:

在此输入图像描述

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

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

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

如何保留左图中的图例顺序,但修改行打印顺序以匹配右图的顺序?

Tje*_*ebo 3

您现在可能已经找到了解决方案。刚刚看到这个问题仍然“未回答”,这里有一个基于@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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述