Skip to content

Using units with ggplot scales and limits #6129

Closed
@noejn2

Description

@noejn2

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions