如何在ggplot2中更改图例几何体

时间:2016-02-20 21:53:32

标签: r ggplot2 legend

你好我说我绘制了这个箱子图:

library(ggplot2)
DT <- data.frame(
  y = runif(400, max = 2),
  grp = sample(c('M', 'F'),size = 400, replace = T),
  x = rep(as.Date(1:10,origin='2011-01-01'), each = 40)
)
p <- ggplot(DT) + geom_boxplot() + aes(x = x, y = y, group=interaction(x,grp), fill=grp)
p

enter image description here

问题是如何用线条替换图例中的那些小方框(就像我使用graphics一样)

1 个答案:

答案 0 :(得分:2)

最简单的选择可能是使线条不可见,

p + guides(fill = guide_legend(override.aes = list(col=NA)))

或者,您可以覆盖boxplot geom的键,

my_key = function (data, params, size) 
{
    grid::rectGrob(height=grid::unit(2,"mm"), 
             gp = grid::gpar(col = NA, 
                       fill = scales::alpha(data$fill, data$alpha), 
                       lty = data$linetype))
}
GeomBoxplot$draw_key <- my_key
p

(如果你需要在同一个会话中使用原文,最好先克隆GeomBoxplot。)