Based on @akrun's suggestion on how to determine in which case we were (deleted), I found that I did what I requested:
plot_it <- function(dat, x, y, fill) { lst <- as.list(match.call()) if(is.character(lst$fill)){ fillN <- shQuote(fill) } else{ fillN <- quo_name(enquo(fill)) } x <- enquo(x) y <- enquo(y) xN <- quo_name(x) yN <- quo_name(y) p <- ggplot(data=dat, aes_string(x=xN, y=yN, fill=fillN)) + geom_bar(stat="identity") return(p) }
It turns out that this does not actually do what I had in mind, since it assigns the quoted value as a factor for the assignment of colors. Not the actual color.
I came up with this, it seems to work, but not very elegantly:
plot_it <- function(dat, x, y, fill) { lst <- as.list(match.call()) if(!(type_of(lst$fill)=="symbol" | (type_of(lst$fill)=="string" & length(lst$fill)==1))) stop("Fill must either be a bare name or a vector of length 1.") x <- enquo(x) y <- enquo(y) xN <- quo_name(x) yN <- quo_name(y) if(is.character(lst$fill)){ dat[,"fillN"] <- fill fillN <- fill p <- ggplot(data=dat, aes_string(x=xN, y=yN, fill = shQuote(fillN))) + scale_fill_manual(name="fill", values=setNames(fillN,fillN)) } else{ fillN <- quo_name(enquo(fill)) p <- ggplot(data=dat, aes_string(x=xN, y=yN, fill = fillN)) } p <- p + geom_bar(stat="identity") return(p) }
Any idea to make this a little more elegant?
source share