【问题标题】:Add legend of geom_boxplot to legend of geom_violin plot将 geom_boxplot 的图例添加到 geom_violin 图的图例中
【发布时间】:2018-01-11 12:23:32
【问题描述】:

我有以下代码:

librery(ggplot2)
ggplot( mtcars ) + 
  geom_violin(  
    aes(
      x = factor(cyl), 
      y = mpg, 
      fill = factor(cyl)
    )
  ) +   
  geom_boxplot( 
    aes( 
      x = factor(cyl),
      y = qsec,
      fill = "blue"
    ),
    width = 0.3,
    alpha = 0.4
  )

生成如下图

情节看起来不错,但我想有不同的传说:

  • 4 到 6 只显示颜色
  • 'blue' 显示箱线图符号,但没有背景颜色,并带有 图例“箱线图 qsec”

我确信这是可能的(ggplot 一切皆有可能......)但是如何?

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    在 ggplot 中,每种美学都有一个图例,您已经为小提琴使用了填充,因此您可以为箱线图使用颜色来制作两个单独的图例。在aes 之外指定箱线图的fill,并在scale_color_manual 中手动指定颜色。 这是一种方法:

    ggplot(mtcars ) + 
      geom_violin(  
        aes(
          x = factor(cyl), 
          y = mpg, 
          fill = factor(cyl)
        )
      ) +   
      geom_boxplot( 
        aes( 
          x = factor(cyl),
          y = qsec,
          color = "blue"),
        width = 0.3,
        alpha = 0.4,
        fill = "blue"
      )+
      +
      scale_color_manual("The QSECS", labels = "text", values = "blue" ) +
      guides(fill = guide_legend(title = "Cylinders"))
    

    【讨论】:

    • 谢谢 - 看起来非常漂亮和干净。在此之后:如何将“颜色”更改为“QSECS”(或任何其他文本),将“因子(cyl)”更改为“圆柱体”?以及将图例文本“蓝色”更改为任何其他文本?
    • @Rainer 很高兴为您提供帮助,添加了两种更改图例的方法。
    • labels = "other text" 添加到scale_color_manual 正在更改图例标签。
    • 非常感谢 - 看起来很完美。
    猜你喜欢
    • 2020-12-22
    • 2022-01-23
    • 2018-05-11
    • 2021-09-23
    • 2021-02-22
    • 1970-01-01
    相关资源
    最近更新 更多