Skip to content

Commit aaa2d44

Browse files
authored
use approx instead of nearest match when placing secondary ticks (#4857)
1 parent c51fa48 commit aaa2d44

13 files changed

+151
-140
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# ggplot2 (development version)
22

3+
* Secondary axis ticks are now positioned more precisely, removing small visual
4+
artefacts with alignment between grid and ticks (@thomasp85, #3576)
5+
36
* Improve `stat_function` documentation regarding `xlim` argument. (@92amartins, #4474)
47

58
* `qplot()` is now formally deprecated (@yutannihilation, #3956).

R/axis-secondary.R

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,16 @@ AxisSecondary <- ggproto("AxisSecondary", NULL,
210210
# Create mapping between primary and secondary range
211211
full_range <- self$transform_range(old_range)
212212

213+
# Remove duplicates in the expanded area of the range that can arise if
214+
# the transformation is non-monotonic in the expansion. The split ensures
215+
# the middle duplicated are kept
216+
duplicates <- c(
217+
!duplicated(full_range[seq_len(self$detail/2)], fromLast = TRUE),
218+
!duplicated(full_range[-seq_len(self$detail/2)])
219+
)
220+
old_range <- old_range[duplicates]
221+
full_range <- full_range[duplicates]
222+
213223
# Get break info for the secondary axis
214224
new_range <- range(full_range, na.rm = TRUE)
215225

@@ -226,8 +236,7 @@ AxisSecondary <- ggproto("AxisSecondary", NULL,
226236

227237
# Map the break values back to their correct position on the primary scale
228238
if (!is.null(range_info$major_source)) {
229-
old_val <- lapply(range_info$major_source, function(x) which.min(abs(full_range - x)))
230-
old_val <- old_range[unlist(old_val)]
239+
old_val <- approx(full_range, old_range, range_info$major_source)$y
231240
old_val_trans <- scale$trans$transform(old_val)
232241

233242
# rescale values from 0 to 1
@@ -243,8 +252,7 @@ AxisSecondary <- ggproto("AxisSecondary", NULL,
243252
}
244253

245254
if (!is.null(range_info$minor_source)) {
246-
old_val_minor <- lapply(range_info$minor_source, function(x) which.min(abs(full_range - x)))
247-
old_val_minor <- old_range[unlist(old_val_minor)]
255+
old_val_minor <- approx(full_range, old_range, range_info$minor_source)$y
248256
old_val_minor_trans <- scale$trans$transform(old_val_minor)
249257

250258
range_info$minor[] <- round(

tests/testthat/_snaps/coord-flip/turning-off-secondary-title-with-coord-flip.svg

Lines changed: 12 additions & 12 deletions
Loading

tests/testthat/_snaps/coord-transform/sec-axis-with-coord-trans.svg

Lines changed: 22 additions & 22 deletions
Loading

tests/testthat/_snaps/guides/guide-axis-customization.svg

Lines changed: 6 additions & 6 deletions
Loading

0 commit comments

Comments
 (0)