I am encountering some issues when defining a secondary axis in ggplot2. In particular I can't define the transformation I would like to apply to the axis without quoting the data.
Here the code:
mtcars %>%
ggplot()+
geom_line(aes(x=mpg, y=wt), col="red")+
geom_line(aes(x=mpg, y=disp*( max(wt) / max(disp) ) ), col="blue" )+
scale_y_continuous(sec.axis = sec_axis(~./(max(wt) / max(disp)), name="disp"))
And I get the error:
Error in rlang::eval_tidy(rlang::f_rhs(self$trans), data = range, env = rlang::f_env(self$trans)) :
object 'wt' not found
When defining sec.axis = sec_axis(~./(max(wt) / max(disp))
the variable wt
and disp
are contained in the mtcars
dataset. Why is it returning the error?
I can get around it by doing
... sec_axis(~./(max(mtcars$wt) / max(mtcars$disp)) ...
However I would like to apply these transformation without quoting the dataset every time. This is because before plotting the data I would like to apply some transformations such as
my_df %>% groupby(...) %>% summarize(...) %>% mutate(...) %>% ggplot(...)
When plottting the data in such way I cannot refer to an existing table because the table doesn't exit but it is being created for the sole purposes of plotting.
Can anyone help? Thanks