Create a new custom point shape for ggplot2

122 Views Asked by At

I would like to use a new point shape on ggplot2, and use it the same way as geom_point().

I know that ggstar implements some new shapes, but I would like to use the following:

Desired shape

It's created just combining a circle with a rect, creating this new shape

joining shapes

I think the code of ggstar to create the shapes is in the following link, but I couldn't understand and recreate it:

https://github.com/xiangpin/ggstar/blob/master/R/primitive.R

I see Allan Cameron created a new grob on this answer, but I don't know how to recreate this new shape, and add the ability to use angle argument

1

There are 1 best solutions below

1
On

Building on the answer from @AllanCameron and the suggestion from @Friede in his comment here is one possible approach to achieve your desired result which also allows for an angle argument:

library(ggplot2)
library(purrr)
library(dplyr)
library(grid)
library(ggpmisc)

custom_shape <- function(size, angle = 0) {
  vp <- viewport(angle = angle)
  grobTree(
    rectGrob(
      x = unit(0.5, "npc"),
      y = unit(0.5, "npc"),
      width = unit(size, "mm"),
      height = unit(size / 2, "mm"),
      gp = gpar(fill = "blue"),
      vjust = 0,
      vp = vp
    ),
    circleGrob(
      x = unit(0.5, "npc"),
      y = unit(0.5, "npc"),
      r = unit(size / 2, "mm"),
      gp = gpar(fill = "red"),
      vp = vp
    )
  )
}

# Plot 10 random points
set.seed(69)

tibble(
  x = rnorm(10), y = rnorm(10),
  shape = purrr::map2(
    sample(seq(10)), 
    seq(0, 360, length.out = 10),
    custom_shape
  )
) %>%
  ggplot() +
  geom_grob(aes(x, y, label = shape))