Search code examples
juliarcall

Why am i getting an error when trying to work with ggplot in Julia?


I call the ggplot package in Julia as shown in this website: https://avt.im/blog/2018/03/23/R-packages-ggplot-in-julia. I use the package as shown in that website and everything works fine.

Now i plot the average marginal effects in Julia using the Effects package. I want to plot it using ggplot here is the data i have:

df = effects(design, m1)

enter image description here

Here is my ggplot code and the error:

ggplot(df, aes(unemploy, workhours, group = sex, shape= sex, linetype=sex)) + 
  geom_point(position=position_dodge(width=0.15)) +
  geom_errorbar(aes(ymin = lower, ymax = upper),width = 0.1,
                linetype = "solid",position=position_dodge(width=0.15))+
  geom_line(position=position_dodge(width=0.15))  

UndefVarError: sex not defined

Stacktrace:
 [1] top-level scope
   @ In[131]:1
 [2] eval
   @ ./boot.jl:360 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1116

I tried this code before in R on the same dataframe and it worked fine, so the problem i guess is that ggplot is not reading the data as it should. Could someone help me to get around this problem?


Solution

  • Your link actually explains it in this small snippet:

    ggplot(d, aes(x=:x,y=:y)) + geom_line()
    

    Note that the aes function uses Julia symbols like :x to refer to data frame columns.

    In your line aes(unemploy, workhours, group = sex, shape= sex, linetype=sex), sex is treated like any other variable in Julia, specifically that Julia tries to look for the existing variable sex in the code and the object it references. It was not found in your code, hence the UndefVarError.

    Non-standard evaluation grants R's aes the capability to see group=sex and treat sex as a name instead of trying to evaluate it. This slightly resembles how Julia's macros work on unevaluated expressions prior to the compile phase, but R has a very different style.