当我有包装标签时,如何更改图例键大小?

How can I change the legend key size when I have a wrapped label?

我正在制作一个带有长图例标签的图,我想调整填充键的大小,使其成为正方形(即不延伸到标签文本的顶部和底部)。我可以使用 theme()guide_legend() 使图例键的高度达到我想要的高度,但我不能让它比包装文本的高度小。有没有办法覆盖这个最小尺寸?

包括最少的代码示例——第一个成功地使键变高,但第二个未能使键变短(这是我想要发生的)。

theme_set(theme_bw())
df <- data.frame(x = rnorm(100))

ggplot(df) + 
  geom_histogram(
    aes(x = x, fill = 'this text is \nway too long to \nfit on one line')) + 
  theme(legend.key.height = unit(50, 'mm'))

ggplot(df) + 
  geom_histogram(
    aes(x = x, fill = 'this text is \nway too long to \nfit on one line')) + 
  theme(legend.key.height = unit(0.001, 'mm'))

我不知道有什么方法可以在本机执行此操作。我认为你的两个选择是沿着编写你自己的绘制键的路线,就像 link Stefan 提供的那样,或者尝试一些更简单但更多的 hack,像这样:

legend_height <- 8

ggplot(df) + 
  geom_histogram(
    aes(x = x, fill = 'this text is \nway too long to \nfit on one line'),
    key_glyph = draw_key_path) + 
  guides(fill = guide_legend(override.aes = list(
    size = legend_height, colour = "#f8766d")))

或者,使用 legend_height <- 2,您将得到: