r-quantities / units

Measurement units for R
https://r-quantities.github.io/units
172 stars 27 forks source link

Secondary axis with `scale_units` #326

Closed ekatko1 closed 1 year ago

ekatko1 commented 1 year ago

With the ggforce package it was possible to use the sec.axis option to specify a secondary axis. However, since the merge of scale_units into the units package, this is no longer possible. The scale_units function passes arguments to the ggplot2::continous_scale function which does not have a sec.axis option.

Below is an example of how this could work, if implemented.

library(units)
df = cars
df$speed = set_units(df$speed, mph)
df$dist  = set_units(df$dist,  ft)

library(ggplot2)
ggplot(aes(x=speed, y=dist), data=df) + geom_point() + 
  scale_y_units(sec_axis=dup_axis(~.*set_units(0.3048, m/ft)))

Currently, the last line returns:

Error in ggplot2::continuous_scale(c("y", "ymin", "ymax", "yend", "yintercept",  : 
  unused argument (sec_axis = <environment>)

Vignette on secondary axes in ggplot2 (e.g. using ggplot2::scale_continous): https://ggplot2.tidyverse.org/reference/sec_axis.html

Enchufa2 commented 1 year ago

Restored. But note that secondary axes do not work as you expect. They are pretty limited, because scales are not retrained and they just inherit the label, or you have to provide it explicitly.

ekatko1 commented 1 year ago

@Enchufa2 Thanks for the quick fix! Yes, this is how they were withggforce. Having secondary axes with units can be a future enhancement (or not).