Skip to content

NA limits in coords #2907

Closed
Closed
@eliocamp

Description

@eliocamp

Setting NA in limits of coords in a similar fashion to scales ends up in an error.

library(ggplot2)

ggplot(cars, aes(speed, dist)) +
   geom_point() +
   coord_cartesian(ylim = c(25, NA))  # emulating scale_y_continuous(limits = c(25, NA))
#> Error in if (zero_range(range)) zero_width else diff(range): missing value where TRUE/FALSE needed

Created on 2018-09-21 by the reprex package (v0.2.0).

I've tinker a bit and found that the error is in this line:

range <- range(scale$transform(limits))

Adding this:
limits <- ifelse(is.na(limits), scale$get_limits(), limits)
solves the issue in this case.

library(ggplot2)

scale_range <- function(scale, limits = NULL, expand = TRUE) {
   expansion <- if (expand) ggplot2:::expand_default(scale) else c(0, 0)
   
   if (is.null(limits)) {
      scale$dimension(expansion)
   } else {
      limits <- ifelse(is.na(limits), scale$get_limits(), limits)
      range <- range(scale$transform(limits))
      scales::expand_range(range, expansion[1], expansion[2])
   } 
}

assignInNamespace("scale_range", scale_range, ns = "ggplot2")

ggplot(cars, aes(speed, dist)) +
   geom_point() +
   coord_cartesian(ylim = c(25, NA))  

Created on 2018-09-21 by the reprex package (v0.2.0).

I'm not versed enough on how ggplot2 handles coords to know if it's a robust fix across different coords, though.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions