1
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(shape = "square", color = "blue")

I have a function that will accept the shape and color parameters, which will be passed to geom_point. I need to check if the input is valid. So I need to do something like:

stopifnot(shape %in% all_valid_shapes) ditto for color

So where can I get those lists?

  • Duplicate for color part: https://stackoverflow.com/questions/13289009/check-if-character-string-is-a-valid-color-representation – MrFlick Nov 18 '20 at 03:48

1 Answers1

4

See this existing question for validating color.

For the shapes, you could use the un-exported ggplot function that validates the shape names

ggplot2:::translate_shape_string(4)       # ok
ggplot2:::translate_shape_string("cross") # ok
ggplot2:::translate_shape_string("oops")  # bad
ggplot2:::translate_shape_string(30)      # bad

You can see if it throws an error or not. But because this is an unexported function, it is not guaranteed to work or be maintained in future versions of ggplot2 so use at your own risk.

Or there is code in the ggplot specs vignette vignette("ggplot2-specs", package="ggplot2") that seems to give a list of all the possible values. you could check potential string values against that list.

shape_names <- c(
  "circle", paste("circle", c("open", "filled", "cross", "plus", "small")), "bullet",
  "square", paste("square", c("open", "filled", "cross", "plus", "triangle")),
  "diamond", paste("diamond", c("open", "filled", "plus")),
  "triangle", paste("triangle", c("open", "filled", "square")),
  paste("triangle down", c("open", "filled")),
  "plus", "cross", "asterisk"
)
Paul
  • 8,734
  • 1
  • 26
  • 36
MrFlick
  • 195,160
  • 17
  • 277
  • 295