0

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

Marco De Virgilis
  • 982
  • 1
  • 9
  • 29
  • AFAIK you must specify your dataset in `sec_axis`. I would therefore suggest you split your computation in two steps. First you do: `my_df <- my_df %>% groupby(...) %>% summarize(...) %>% mutate(...)`. Second you `ggplot` it. That should not make your code less readable or less maintainable IMHO. – symbolrush Mar 25 '19 at 11:41
  • The problem is I have to create a lot of plots and I would like to avoid creating so many temporary dfs – Marco De Virgilis Mar 25 '19 at 11:47
  • Just delete them after usage with `rm(my_df)`. – symbolrush Mar 25 '19 at 11:58
  • 1
    Possible duplicate of [Plot with 2 y axes, one y axis on the left, and another y axis on the right](https://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left-and-another-y-axis-on-the-right) – symbolrush Mar 25 '19 at 14:54

0 Answers0