如何将 ggplot2 中图例键字形的形状更改为六边形?

LDT*_*LDT 4 r legend ggplot2

我已经奋斗了很长一段时间来寻找一种方法来改变带有六边形的 ggplot2 的图例键。非常感谢任何帮助或指导!

library(ggplot2)
set.seed(123)
ggplot(iris) +
  geom_jitter(aes(x=Species,y=Sepal.Length,color=Species),width=0.25) +
  guides(color= guide_legend(override.aes = list(shape = 21)))
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2021 年 11 月 13 日创建(v2.0.1)

use*_*650 6

您可以使用命令创建键grid,然后geom_使用key_glyph参数传递给 a。

一个简单的例子:

library(grid)
library(ggplot2)

draw_key_hex <- function (data, params, size) {
    # hexagon vertex coordinates 
    v <- list(x = c(0.95, 0.725, 0.275, 0.05, 0.275, 0.725), 
              y = c(0.5, 0.110288568297003, 0.110288568297003, 0.5, 0.889711431702997, 0.889711431702997))
    # hexagon grob
    polygonGrob(v$x, v$y, 
                gp = gpar(col = data$colour,
                          fill = alpha(data$fill, data$alpha)))
}

set.seed(123)
ggplot(iris, aes(x=Species,y=Sepal.Length,color=Species)) +
  geom_jitter(width=0.25, key_glyph=draw_key_hex) 
Run Code Online (Sandbox Code Playgroud)

# or with fill
set.seed(123)
ggplot(iris, aes(x=Species,y=Sepal.Length,color=Species, fill=Species)) +
  geom_jitter(width=0.25, key_glyph=draw_key_hex) 
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案。您应该添加输出的图片。可能值得指出的是,如果六边形看起来有点小,您仍然可以通过添加行“guides(color=guide_legend(override.aes = list(size = 20)))”来增加其大小 (3认同)