Description
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:
Lines 178 to 181 in a4be39d
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