如何在 ggplot2 中将图例键字形的形状更改为六边形?
How do I change the shape of the legend key glyph to a hexagon in 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)))
由 reprex package (v2.0.1)
于 2021-11-13 创建
您可以使用 grid
命令创建密钥,然后使用 key_glyph
参数传递给 geom_
。
一个简单的例子:
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)
# 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)
我一直在努力寻找一种方法来更改带有六边形的 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)))
由 reprex package (v2.0.1)
于 2021-11-13 创建您可以使用 grid
命令创建密钥,然后使用 key_glyph
参数传递给 geom_
。
一个简单的例子:
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)
# 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)