代码之家  ›  专栏  ›  技术社区  ›  tjebo

多重美学图例的更改顺序

  •  1
  • tjebo  · 技术社区  · 7 年前

    我有几种美学,并希望指定每种美学的图例绘制顺序。 大多数线程都是关于更改项目顺序的 在内部 美学,但这不是我的问题。在我的示例中,我想指定填充图例的位置。有趣的是,颜色图例绘制在填充图例的顶部,但在底部绘制图例时,颜色图例位于填充图例的“右侧”。对于像我这样的从左到右的读者来说,这似乎有些随机,他们也喜欢从上到下阅读。

    该图显然有点随机,只是很快为reprex制作的。

    library(ggplot2)
    
    ggplot(mtcars) +
      geom_boxplot(aes(cyl, hp, fill = as.character(gear))) +
      geom_boxplot(aes(cyl, disp, color = as.character(cyl))) +
      labs(fill = 'fill', color = 'color')
    
    # here I would like the fill legend to be *above* the color legend
    

    ggplot(mtcars) +
      geom_boxplot(aes(cyl, hp, fill = as.character(gear))) +
      geom_boxplot(aes(cyl, disp, color = as.character(cyl))) +
      labs(fill = 'fill', color = 'color') +
      theme(legend.position = 'bottom')
    
    # here I would like the fill legend to be *right* and the color legend left
    

    reprex package (v0.2.1)

    1 回复  |  直到 7 年前
        1
  •  8
  •   Martin Schmelzer    6 年前

    你可以使用 order 选择 guide_legend

    ggplot(mtcars) +
      geom_boxplot(aes(cyl, hp, fill = as.character(gear))) +
      geom_boxplot(aes(cyl, disp, color = as.character(cyl))) +
      labs(fill = 'fill', color = 'color') +
      guides(fill  = guide_legend(order = 1),
             color = guide_legend(order = 2))
    

    enter image description here

    推荐文章