调整由 key_glyph ggplot 生成的图例字形的高度和宽度

Adjust Height and Width of Legend Glyphs Generated by key_glyph ggplot

我很高兴地发现我可以通过将 key_glyph = draw_key_rect 添加到我的 geom 层来更改图例中使用的字形。我想通过 Timo Grossenbacher:

使图例更宽更短以类似于此地图中的图例

我试过调整 scale_fill_manual(guide = guide_legend(keyheight = unit(0.01, units = "mm") , keywidth = unit(40, units = "mm"))) 来改变图例的尺寸,但似乎只有当我把字形变大时才有效。我似乎无法将键高设置得更小。

是否有更好的调整图例字形尺寸的方法?

此处简化代码:

df <- data_frame(x_value = c(1:10),
                 y_value = c(rev(1:10)),
                 value = c("a","a","a","a","b","b","b","b","c","c"))
library(ggplot2)

ggplot(data = df) + 
  geom_point(aes(x_value, y_value, fill = value),
             shape = 21,
             size = 9,
             key_glyph = draw_key_rect) +
  theme(legend.justification = c(0,0), # set which corner of legend legen.position references
        legend.position = c(0.05, 0.04)) +
  scale_fill_manual(values = c("red", "green", "blue"),
                    guide = guide_legend(direction = "horizontal",
                                         keyheight = unit(0.01, units = "mm"),
                                         keywidth = unit(40, units = "mm"),
                                         title.position = 'top',
                                         label.position = "bottom"))

。或者这是另一个稍微有点老套的解决方案。

问题似乎出在 geom_point 中的大小参数,因此您可以伪造美学,特别是使用线条,例如像这样:

  • 画透明线(geom_line(alpha = 0))
  • geom_line 制作颜色图例,使用与填充颜色相同的颜色。
  • 将颜色图例的 alpha 设置为 1 (override.aes)
  • 删除填充图例。
  • 控制theme中的图例高度
library(ggplot2)

df <- data.frame(x_value = c(1:10),
                 y_value = c(rev(1:10)),
                 value = c("a","a","a","a","b","b","b","b","c","c"))

ggplot(data = df) + 
  geom_point(aes(x_value, y_value, fill = value), shape = 21, size = 7, 
             show.legend = FALSE) + # remove fill legend
  geom_line(aes(x_value, y_value, color = value), 
            alpha = 0, #invisible line. If your data is big, you could create a very small data frame for that
            key_glyph = draw_key_rect) +
  theme(legend.justification = c(0,0), 
        legend.position = c(0.05, 0.04), 
        legend.key.height = unit(0.1, 'in')) + # control height
  scale_fill_manual(values = c("red", "green", "blue")) +
  scale_color_manual(values = c("red", "green", "blue")) +
  guides(color = guide_legend(override.aes = list(alpha = 1), # make line visible in legend 
                              direction = "horizontal",
                              keywidth = unit(20, units = "mm"),
                              title.position = 'top',
                              label.position = "bottom"))

reprex package (v0.3.0)

于 2020 年 2 月 20 日创建

另一种选择是删除 key_glyph 参数并使用 geom_line

中的 size 参数控制字形高度