Skip to content

Feature request: allow function as argument value in scale_*(limits=) #2307

Closed
@econandrew

Description

@econandrew

Request is to allow limits arg in e.g. scale_x_continuous to accept a function which takes the default limits and returns new limits, in parallel with the same functionality in breaks and labels.

At present it seems like the two options are (1) specify literal limits, which is inflexible (2) calculate the preferred limits outside of the ggplot statement, but that is messy and can result in redoing calculations already happening inside ggplot (e.g. for position="stack").

It looks like this may be a one line change in scale-.r's get_limits, but I don't know my way around well enough to be sure.

Motivating example follows.

library(ggplot2)


p <- ggplot(mtcars) + geom_point(aes(cyl,mpg))

p # But suppose we don't like the default y-axis breaks...

# ...we have a general mechanism in breaks= to modify them with a function...
breaker <- function(by) {
  function(limits) {
    low <- floor(limits[1]/by)*by
    high <- ceiling(limits[2]/by)*by
    seq(low, high, by)
  }
}

# ...but it doesn't override the limits so we get an (IMHO) ugly y axis where
# the data exceeds the range of the tick marks...
p + scale_y_continuous(breaks = breaker(10))

# In principle we can function-ise the limits in the same way
limiter <- function(by) {
  function(limits) {
    low <- floor(limits[1]/by)*by
    high <- ceiling(limits[2]/by)*by
    c(low, high)
  }
}

# But for now the best we can do is manually override the limits
p + scale_y_continuous(breaks = breaker(10), limits = limiter(10)(range(mtcars$mpg)))

# Feature request: if limits arg is a function, pass it the existing limits automatically
p + scale_y_continuous(breaks = breaker(10), limits = limiter(10))
#> Warning in is.na(self$limits): is.na() applied to non-(list or vector) of
#> type 'closure'
#> Error in rep(yes, length.out = length(ans)): attempt to replicate an object of type 'closure'

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