0

I'm trying to create a plotly barchart using some tidyeval functionality. I have succeeded in creating a simple barchart but can not seem to make a stacked barchart colored by an attribute. Have been stuck at this for a while and cannot seem to figure out what the error is saying. Any help is appreciated, Thanks!

get_barchart <- function(df, col, xcol, y){
  a <- sym(col)
  col <- enquo(a)
  xcol <- enquo(xcol)
  y_col <- enquo(y)

  df %>%
    group_by(!!col, !!xcol) %>%
    summarise(Total = sum(!!y_col, na.rm = T)) %>%
    plot_ly(x = xcol, y = ~Total, type = "bar",
            color = col, 
            text = ~Total, textposition = 'auto') %>%
    layout(barmode = 'stack')
}
x = "Gender"
get_barchart(data.frame(UCBAdmissions), x, Admit, Freq)

If I comment out the color line, the function works so I'm pretty sure that is what is causing the error but can not seem to understand why.

Mridul Garg
  • 477
  • 1
  • 8
  • 17
  • I found a workaround this- if I use sym for x before passing it to the function, and change the first two lines of the function then it works. I'm still interested in learning as to why the original function does not work if possible – Mridul Garg Apr 05 '18 at 00:57
  • 2
    You have two choices: an interface that takes strings (the contents or value of `col` no matter what expression was supplied by the user) or an interface that takes quoted symbols (the expression supplied to `col` no matter what its value is). In the former case use `sym()`, in the latter case use `enquo()`. Only use `enquo()` on argument names like `col` though (not on `a` as in your snippet). Also the latter case will force you to unquote stuff when calling your function just like you have to unquote stuff when calling dplyr functions. – Lionel Henry Apr 05 '18 at 08:09

0 Answers0