How can I change the legend geometry in ggplot2

霸气de小男生 提交于 2021-02-11 11:50:36

问题


Hello say I plot this boxplot:

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

Question is how can I replace those little boxes in the legend by lines (like I would have using graphics)


回答1:


easiest option might be to make the lines invisible,

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

alternatively, you could overwrite the key for the 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

(probably better to clone GeomBoxplot first if you need the original in the same session).



来源:https://stackoverflow.com/questions/35529516/how-can-i-change-the-legend-geometry-in-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!