简体   繁体   中英

How can I change the legend geometry in ggplot2

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 )

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM