Increase space between legend keys without increasing legend keys

后端 未结 1 1975
谎友^
谎友^ 2020-12-11 05:14

This is a follow-up on https://stackoverflow.com/questions/32275113

The problem is to tweak the legend elements to increase the space between legend keys without sim

相关标签:
1条回答
  • 2020-12-11 06:03

    One solution is to replace lines with points (requires additional geom layer):

    Create plot with invisible points (size = 0 and rectangle shape shape = 15).

    p <- ggplot(d, aes(x, ..density..)) + 
        geom_histogram(fill = "lightblue", color = "black") + 
        geom_vline(data = vlines, mapping = aes(xintercept = x, colour = stat)) +
        geom_point(data = vlines, aes(0, 0, colour = stat), size = 0, shape = 15)
    

    Add legend theme to:

    • Mask background color in legend (legend.key = element_rect(fill = "white"))
    • Create large legend (legend.key.height = unit(3, "cm"))
    • Remove lines (linetype = 0) and make large points (size = 5)

    Code:

    p + 
        theme(legend.direction = "vertical", 
              legend.position = "right",
              legend.key = element_rect(fill = "white"),
              legend.key.height = unit(3, "cm")) +
        guides(color = guide_legend(override.aes = list(linetype = 0, size = 5)))
    

    PS.:

    • This is not a perfect solution as there's a gap between legend label and boxes.
    • If you want lines instead of rectangles use shape = 73
    0 讨论(0)
提交回复
热议问题