Skip to content

Binned scales don't work with limits = function() #6144

Closed
@arcresu

Description

@arcresu

According to the docs, scale_x_binned() and friends can be given a function for limits. However, this fails when a transform is also set.

This example is supposed to make a bar plot counting days in each month (i.e. a binned date scale), and works fine until a limits function is provided:

library(ggplot2)

df <- data.frame(x = seq(as.Date("2024-01-01"), as.Date("2024-06-30"), "day"))

ggplot(df) +
  geom_bar(aes(x)) +
  scale_x_binned(
    breaks = scales::breaks_width("1 month"),
    transform = scales::transform_date(),
    # works if the following line is commented out
    limits = function(x) { x }
  )

# Error in `scale_x_binned()`:
# ! Binned scales only support continuous data.

Looking through the code, it seems that ScaleBinned itself is fine (all access goes through ScaleBinned$get_limits() which handles function values properly), but the binned_scale() constructor causes the error here:

ggplot2/R/scale-.R

Lines 321 to 324 in ddd207e

transform <- as.transform(transform)
if (!is.null(limits)) {
limits <- transform$transform(limits)
}

In that snippet, limits is the bare value passed in by the user, so if that's a function then it's forwarded as-is to the transform. The date transform says that a function object is not numeric hence the error.

Found on 3.5.1 but the relevant code is the same on main.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorscales 🐍

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions