【问题标题】:How to reorder overlaying order of geoms but keep legend order intact in ggplot如何重新排序geoms的叠加顺序但在ggplot中保持图例顺序不变
【发布时间】:2018-05-18 22:56:14
【问题描述】:

我知道我可以通过更改分组因子的levels 来切换线绘制顺序(即,哪条线绘制在第一、第二、第三……)。但是,这样做会切换 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))

我可以通过更改levelsid 因子来切换线条绘制顺序:

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

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

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 个图形:

左:因子id 的原始水平顺序 |右:使用relevel

请注意,行已成功重新排序:行 c 从最后打印(因此在顶部)变为首先打印(因此在底部)。

不过,传说也换了顺序!

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

【问题讨论】:

  • 一个肮脏的举动可能是绘制两个geom_linesgeom_line(size = 2, show.legend = FALSE) + geom_line(aes(color=relevel(id, 'c')), size=2)
  • 是的,我知道该怎么做:p。谢谢!但是,考虑到我的实际数据的数量和复杂性,这种方法并不理想。我希望有一些我不知道的隐藏论点,或者比你建议的更直接的方法。
  • scale_colour_manual 中使用breaks 参数:ggplot(dat, aes(x = x, y = y, color = relevel(id, "c"))) + geom_line(size = 2) + scale_colour_manual('id', values = cols, breaks = levels(dat$id))

标签: r ggplot2 legend


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多