How do I change the shape of the legend key to a hexagon shape in ggplot2?

I have been battling for a long time now to find a way to change the shape of the legend key of a ggplot2t to a hexagon shape. Any help or guidance are highly appreciated!

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 = 6)))

Created on 2021-11-13 by the reprex package (v2.0.1)

Here are the available built-in shapes.

library(ggplot2)
# Show a list of available shapes
df_shapes <- data.frame(shape = 0:24)
ggplot(df_shapes, aes(0, 0, shape = shape)) +
  geom_point(aes(shape = shape), size = 5, fill = 'red') +
  scale_shape_identity() +
  facet_wrap(~shape) +
  theme_void()

so shape = 6 is an inverted triangle. Are you looking to create a custom shape?

There is a ggstar package on CRAN that can plot hexagons.

library(ggplot2)
set.seed(123)
ggplot(iris) +
  ggstar::geom_star(aes(x=Species,y=Sepal.Length,fill=Species),
                    color = NA,
                    position = position_jitter(width = 0.25),
                    starshape = "hexagon", size = 2) +
  guides(fill = guide_legend(override.aes = aes(size = 5)))

1 Like

Thank you technocrat for your time and answer. I want to create a hexagon since its not in the list of the available build in shapes. Importantly I want to change the only the shape of the legend.key.

Thank you Jack for your time and answer. I am aware of the ggstars. Such a cool package. I want to change the only the shape of the legend.key and let the point of the plot in a round shape

Looking at the ggstar version, I had to enlarge quite a bit to see that the plotted points were indeed hexagons.

If I needed to do this only on occasion, I'd suppress the legend and create an annotation object to put in its place.

1 Like
library(ggplot2)
set.seed(123)
ggplot(iris) +
  ggstar::geom_star(aes(x=Species,y=Sepal.Length,fill=Species),
                    color = NA,
                    position = position_jitter(width = 0.25),
                    starshape = "hexagon", size = 0) +
  geom_point(aes(x=Species,y=Sepal.Length,color=Species),
             position = position_jitter(width = 0.25)) +
  guides(fill = guide_legend(override.aes = aes(size = 5)))

This is slightly hacky but does what you want!

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.