【问题标题】:Position legend in first plot of facet刻面第一个图中的位置图例
【发布时间】:2011-11-08 09:53:18
【问题描述】:

我想将我的情节图例放入情节中,即刻面的第一个情节中。

下面是一些示例代码:

df=data.frame(
 x=runif(10),
 y=runif(10),
 facet=rep(c("a","b"),5),
 color=rep(c("red","blue"),5))

ggplot(data=df,aes(x=x,y=y,color=color))+
 geom_point()+
 facet_wrap(~facet,ncol=1)

这是结果图:

这就是我想要的大致样子:

感谢您提供的任何帮助!

【问题讨论】:

    标签: r position ggplot2 legend


    【解决方案1】:

    假设你的情节被保存为p

    p + opts(
      legend.position = c(0.9, 0.6), # c(0,0) bottom left, c(1,1) top-right.
      legend.background = theme_rect(fill = "white", colour = NA)
    )
    

    如果您希望图例背景部分透明,请将fill 更改为例如"#ffffffaa"

    【讨论】:

    • 谢谢里奇!这适用于我的示例图,但由于某种原因,当我将这些代码行添加到另一个图时,图例消失了。知道为什么会这样吗?我将我拥有的 opts 代码放在原始帖子中
    • 其他绘图是否保存到不支持透明度的文件类型(可能是 gif)?
    • 或者您是否更改了 legend.position 以使其移到情节边缘?
    • 它被移出了情节......legend.position 中的值与 x 轴上的值不符,出于某种原因。我现在好像有了
    • 图例位置使用的值是相对于绘图区域的,因此c(0,0) 是绘图的左下角,c(1,1) 是右上角。它们不能与 x 轴上的值相同,因为不同的方面可以有不同的比例。
    【解决方案2】:

    或者,基于@Richie Cotton 的回答,因为 opts 现在在 ggplot2 中已被弃用(仍然假设您的情节被定义为 p)

    p + theme(legend.position = c(0.9, 0.6)
              ,legend.background = element_rect(fill = "white", colour = NA))
    

    【讨论】:

      猜你喜欢
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多