Skip to content

Commit 37ed660

Browse files
authored
Better binning algorithm for contours (#4006)
* better binning algorithm. closes #4004 * update news * better results for bins == 1
1 parent 908edc9 commit 37ed660

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

NEWS.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
containing no other data or layers (@clauswilke, #3611, #3905, #3983).
1515

1616
* A bug was fixed in `stat_contour()` when calculating breaks based on
17-
the `bins` argument (@clauswilke, #3879).
17+
the `bins` argument (@clauswilke, #3879, #4004).
1818

1919
* A newly added geom `geom_density_2d_filled()` and associated stat
2020
`stat_density_2d_filled()` can draw filled density contours

R/stat-contour.r

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,16 @@ contour_breaks <- function(z_range, bins = NULL, binwidth = NULL, breaks = NULL)
156156

157157
# If provided, use bins to calculate binwidth
158158
if (!is.null(bins)) {
159+
# round lower limit down and upper limit up to make sure
160+
# we generate bins that span the data range nicely
161+
accuracy <- signif(diff(z_range), 1)/10
162+
z_range[1] <- floor(z_range[1]/accuracy)*accuracy
163+
z_range[2] <- ceiling(z_range[2]/accuracy)*accuracy
164+
165+
if (bins == 1) {
166+
return(z_range)
167+
}
168+
159169
binwidth <- diff(z_range) / (bins - 1)
160170
breaks <- fullseq(z_range, binwidth)
161171

0 commit comments

Comments
 (0)