ggplot2: use label if object exists, otherwise choose default/NULL

Viewed 43

I have a ggplot2 function that includes the following command:

sp <- sp + geom_point() + gs + scale_linetype_manual(values =
            c('solid',  'longdash','dashed', 'twodash', 'dotdash', 'dotted'), labels=labls)

This is used by users with different datasets. If I define the object labls as a vector (e.g. labls=c("cow","horse","chicken")) this works fine, of course. However, I want it to refer to the default labeling when the object does not exist (in this case: 1, 2, 3).

Is there a quick and elegant way to include this condition? I've stumbled upon the "ifelse" function, but am not sure how to use this in reference to the object I'm letting "labels" request?

Thanks

1 Answers

Use labels = waiver() to specify that you want the defaults.

library(ggplot2)

create_plot <- function(df, labels) {
  if (missing(labels)) {
    labels <- waiver()
  }
  
  ggplot(df, aes(Sepal.Length, Sepal.Width, linetype = Species)) +
    geom_line() +
    scale_linetype_manual(values = c('longdash','dashed', 'twodash'), labels = labels)
}

Specifying labels

create_plot(iris, labels = c('A', 'B', 'C'))

Non-default

Not specifying labels and getting the defaults

create_plot(iris)

Default

Related