0

I am trying to set a factor variable that gets called multiple times in a ggplot (e.g., color, factor). I have multiple variables I would like to factor by, and would like to avoid copying my code, and replacing that variable 4 times. If I wasn't plotting I would just use set the variable to

split <- data$npantc_quantile

and substitute it everywhere it appears.

gg_antc_q <- ggplot(data=filter(data, npantc_quantile %in% c(1, 5)),aes(x=delta,y=1-user_response, colour = npantc_quantile, group = npantc_quantile))+
  stat_summary(fun.data = "mean_cl_boot", geom = "point", aes(shape = factor(npantc_quantile)), size = 4)+
  stat_summary(fun.data = "mean_cl_boot", geom = "line")+
  geom_smooth() +
  ggtitle("Quantile Split: Arrows Normal") +
  add_tone_lag_450

However, I know that I need to avoid dollar sign notation when calling anything inside aes(). How else could I call this split without having to rewrite it 4 times?

  • Would bracket notation solve the problem? `data['npantc_quantile']` ? – Ryan Oct 30 '19 at 21:00
  • If you have a `colour=`, you shouldn't need a `group=` if it's the same variable. With ggplot/dplyr, you could set `split<- expr(npantc_quantile)` and then use `!!split` to insert that into the expression. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Oct 30 '19 at 21:00
  • @Ryan. No. Using bracket notation causes the same problem as `$` inside `aes()` -- you need to have the symbols separate from the data source to work properly. – MrFlick Oct 30 '19 at 21:01
  • See also the FAQ on [how to use variables to specify columns in ggplot](https://stackoverflow.com/q/22309285/903061) – Gregor Thomas Oct 31 '19 at 14:51
  • I would suggest defining a variable `split <- "npantc_quantile`, then using `aes_string(x= "delta, [...], group = split)` – alan ocallaghan Oct 31 '19 at 14:51

1 Answers1

0

Using split<- expr(npantc_quantile) with !!split worked to fix my problem. I also removed the group = !!split as it was redundant. Thanks for the suggestion MrFlick