Skip to content

Commit 93136e8

Browse files
committed
sf aspect ratio is flipped, which is why conversions have always been a bit off
1 parent d47a86a commit 93136e8

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

R/ggplotly.R

+11-3
Original file line numberDiff line numberDiff line change
@@ -711,20 +711,28 @@ gg2list <- function(p, width = NULL, height = NULL,
711711
)
712712

713713
# set scaleanchor/scaleratio if these are fixed coordinates
714+
# the logic here is similar to what p$coordinates$aspect() does,
715+
# but the ratio is scaled to the data range by plotly.js
714716
fixed_coords <- c("CoordSf", "CoordFixed", "CoordMap", "CoordQuickmap")
715717
if (inherits(p$coordinates, fixed_coords)) {
716718
axisObj$scaleanchor <- anchor
717719
ratio <- p$coordinates$ratio %||% 1
718-
# a la CoordSf$aspect
720+
axisObj$scaleratio <- if (xy == "y") ratio else 1 / ratio
721+
719722
if (inherits(p$coordinates, "CoordSf")) {
720723
if (isTRUE(sf::st_is_longlat(rng$crs))) {
721724
ratio <- cos(mean(rng$y_range) * pi/180)
722725
}
726+
# note how ratio is flipped in CoordSf$aspect() vs CoordFixed$aspect()
727+
axisObj$scaleratio <- if (xy == "y") 1 / ratio else ratio
723728
}
724-
axisObj$scaleratio <- if (xy == "y") ratio else 1 / ratio
725729
}
726730

727-
# TODO: should we implement aspect ratios?
731+
# TODO: seems like we _could_ support this with scaleanchors,
732+
# but inverse transform by the panel ranges?
733+
# also, note how aspect.ratio overwrites fixed coordinates:
734+
# ggplot(mtcars, aes(wt, mpg)) + geom_point() + coord_fixed(0.5)
735+
# ggplot(mtcars, aes(wt, mpg)) + geom_point() + coord_fixed(0.5) + theme(aspect.ratio = 1)
728736
if (!is.null(theme$aspect.ratio)) {
729737
warning(
730738
"Aspect ratios aren't yet implemented, but you can manually set",

tests/testthat/test-ggplot-sf.R

+11
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,14 @@ test_that("geom_sf() with basic polygons and points.", {
5454
expect_equivalent(l$data[[2]]$mode, "lines")
5555
expect_equivalent(l$data[[3]]$mode, "markers")
5656
})
57+
58+
test_that("sf aspect ratio is correct", {
59+
skip_if_not_installed("sf")
60+
61+
p <- ggplot(nc) + geom_sf()
62+
63+
l <- save_outputs(p, "sf-aspect")
64+
65+
expect_equivalent(l$layout$xaxis$scaleanchor, "y")
66+
expect_equal(l$layout$xaxis$scaleratio, 0.81678435872298)
67+
})

0 commit comments

Comments
 (0)