Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using units with ggplot scales and limits #6129

Closed
noejn2 opened this issue Oct 3, 2024 · 1 comment
Closed

Using units with ggplot scales and limits #6129

noejn2 opened this issue Oct 3, 2024 · 1 comment

Comments

@noejn2
Copy link

noejn2 commented Oct 3, 2024

Working with data using the units and ggplot2 package, I found that setting up limits is not straight forward. I do not think this is the intended use, but I may be wrong.

The following should not work, since ylimit argument is not set in units.

data.frame(x = c(1,2,3),
           y = units::as_units(c(2,3,1),"km")) |> 
  ggplot(aes(x=x, y=y)) +
  geom_point() +
  xlim(0, NA) +
 ylim(0, NA)

So, my initial approach was to set the following just to find out it does not work either

data.frame(x = c(1,2,3),
           y = units::as_units(c(2,3,1),"km")) |> 
  ggplot(aes(x=x, y=y)) +
  geom_point() +
  xlim(0, NA) +
 ylim(units::as_units(0, "km"), units::as_units(0, "km"))

Notice that the arguments units::as_units(0, "km") and units::as_units(NA, "km") do not give an error. Yet, I get an error when rendering the plot.

The current solution uses units::scale_y_units(), but it is not straight forward or documented as a solution to this problem anywhere.

data.frame(x = c(1,2,3),
           y = units::as_units(c(2,3,1),"km")) |> 
  ggplot(aes(x=x, y=y)) +
  geom_point() +
  xlim(0, NA) +
  units::scale_y_units(
    limits = c(0, NA)
  )

Is this the intended approach when using units and ggplot scales and limits?

@teunbrand
Copy link
Collaborator

Hi there, thanks for the report.

It seems like the units package has recently added support for functions like ylim() but this hasn't arrived on CRAN yet.
Your second example works with their development version:

# remotes::install_github("r-quantities/units")
library(ggplot2)
library(units)

data.frame(x = c(1,2,3),
           y = units::as_units(c(2,3,1),"km")) |> 
  ggplot(aes(x=x, y=y)) +
  geom_point() +
  xlim(0, NA) +
  ylim(units::as_units(0, "km"), units::as_units(NA, "km"))

Created on 2024-10-03 with reprex v2.1.1

The state of the scale_y_units() documentation, or more generally —the level of units/ggplot2 interoperability— is outside the control of ggplot2 and should be raised with the units authors. As such, I think this issue should be closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants