I got this message "Error in FUN(X[[i]], ...) : object 'share' not found" when running ggplot2 inside a function. It works fine if I run it outside a function.
Any idea? Thanks so much!
NOTE: I need to pass 'share' as an argument since this function will be applied to some other variables besides 'share'.
df <- data.frame(own.manu = c("AO", "AO", "AO", "Own", "Own"), brand = c('A', "B", "C", "D", "E"), share = c(.1, .2, .3, .25, .15))
createPlot <- function(myvar, mydata) {
out <- ggplot2::ggplot(environment=environment()) +
ggplot2::geom_bar(ggplot2::aes(y = myvar, x = own.manu, fill = brand), stat = "identity", position = ggplot2::position_stack(reverse = TRUE), data = mydata) +
ggplot2::scale_y_continuous(labels = scales::percent_format()) +
ggplot2::geom_text(data = mydata, ggplot2::aes(x = own.manu,
y = myvar,
label = ifelse(myvar >= 0.05, paste0(sprintf("%.0f", myvar*100),"%"),"")),
position = ggplot2::position_stack(vjust=0.5))
out
}
out2 <- createPlot(myvar = share, mydata = df)