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

我有一个函数可以接受shapeandcolor参数,它会被传递给 geom_point。我需要检查输入是否有效。所以我需要做类似的事情:

stopifnot(shape %in% all_valid_shapes) 颜色同上

那么我在哪里可以得到这些列表呢?

4

1 回答 1

4

请参阅此现有问题以验证颜色

对于形状,您可以使用ggplot验证形状名称的未导出函数

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

您可以查看它是否引发错误。但是因为这是一个未导出的函数,所以不能保证在 ggplot2 的未来版本中工作或维护它,所以使用风险自负。

或者 ggplot 规范小插图中的代码vignette("ggplot2-specs", package="ggplot2")似乎给出了所有可能值的列表。您可以根据该列表检查潜在的字符串值。

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"
)
于 2020-11-18T03:52:46.760 回答