Skip to content

Passing a function to breaks= in stat/geom_contour does not work (as long as both bins= and binwidth= are NULL) #5686

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

Closed
trekonom opened this issue Feb 9, 2024 · 0 comments · Fixed by #5703
Labels
bug an unexpected problem or unintended behavior layers 📈
Milestone

Comments

@trekonom
Copy link

trekonom commented Feb 9, 2024

When answering this question on SO I stumbled over an issue when passing a function to the breaks= argument of geom_contour, i.e. passing a function to breaks= has no effect when both bins= and binwidth= are NULL.

As can be seen from the minimal reproducible example below, instead of four contour lines we get the default lines corresponding to the breaks returned by pretty(z_range, 10):

library(ggplot2)

v <- ggplot(faithfuld, aes(waiting, eruptions, z = density))

# Does not work: Expect 4 contour lines
v +
  geom_contour(
    breaks = \(z_range, binwidth) {
      seq(z_range[1], z_range[2], length.out = 4)
    }
  )

I had a look at the source and the issue seems to be that when a function is passed to breaks but both bins= and binwidth= are NULL (which is the default) contour_breaks() will return the default breaks:

ggplot2/R/stat-contour.R

Lines 178 to 181 in a4be39d

if (is.null(bins) && is.null(binwidth)) {
breaks <- pretty(z_range, 10)
return(breaks)
}

A work-around would be to set one of the arguments to a non-NULL value, i.e. after adding binwidth=1 the breaks are computed according to the function passed to breaks=:

# Works if one sets binwidth or bins to a non-NULL value
v +
  geom_contour(
    binwidth = 1,
    breaks = \(z_range, binwidth) {
      seq(z_range[1], z_range[2], length.out = 4)
    }
  )

Created on 2024-02-09 with reprex v2.1.0

@teunbrand teunbrand added layers 📈 bug an unexpected problem or unintended behavior labels Feb 23, 2024
@teunbrand teunbrand added this to the ggplot2 3.5.1 milestone Mar 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug an unexpected problem or unintended behavior layers 📈
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants