本文介绍了增加图例键之间的空间而不增加图例键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于



编辑基于PoGibas聪明的解决方法,下面是所需结果的屏幕截图,包括在这里以确保目的清晰: $ b

附注:




  • 这是一个完美的解决方案,因为在图例标签和盒子之间存在差距。

  • 如果您需要线条而不是矩形,请使用 shape = 73 li>

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 simultaneously extending the legend keys themselves. The solution is likely to be in tweaking the correct legend theme option.

Desired result: more vertical space between the legend key text labels, but without stretching the legend key lines.

d <- data.frame(x = mtcars$mpg, y = 0.10)
vlines <- rbind(aggregate(d[1], d[2], mean),
                aggregate(d[1], d[2], median))
vlines$stat <- rep(c("mean", "median"), each = nrow(vlines)/2)
library("ggplot2")
ggplot(data = d, aes(x = x, y = ..density..)) +
    geom_histogram(fill = "lightblue", color = "black") +
    geom_vline(data = vlines, mapping = aes(xintercept = x, colour = stat),
            show.legend = TRUE) +
    theme(legend.direction = "vertical",
        legend.position = "right",
        #          legend.key = element_rect(size = 2),
        legend.key.size = unit(3, "cm"),
        #          legend.key.width = unit(2, "cm"),
        #          legend.key.height = unit(1, "cm")
        )

Increasing legend.key.size, as suggested in answers to the linked question (see above), has the undesired side effect of increasing the vertical lines as well.

Edit Based on PoGibas's clever workaround, here's a screenshot of the desired result, included here to make sure the purpose is clear:

Following PoGibas, I used: shape = 73, legend.key.height = unit(2, "cm") and size = 6 inside the color guide.

解决方案

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

这篇关于增加图例键之间的空间而不增加图例键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:04