1+ context(" Fixed coordinates" )
2+
3+ # Expect trace function
4+ expect_traces <- function (gg , n_traces , name ) {
5+ stopifnot(is.ggplot(gg ))
6+ stopifnot(is.numeric(n_traces ))
7+ save_outputs(gg , paste0(" coord_fixed-" , name ))
8+ L <- gg2list(gg )
9+ all_traces <- L $ data
10+ no_data <- sapply(all_traces , function (tr ) {
11+ is.null(tr [[" x" ]]) && is.null(tr [[" y" ]])
12+ })
13+ has_data <- all_traces [! no_data ]
14+ expect_equal(length(has_data ), n_traces )
15+ list (traces = has_data , layout = L $ layout )
16+ }
17+
18+ # Data where x ranges from 0-10, y ranges from 0-30
19+ set.seed(202 )
20+ dat <- data.frame (xval = runif(40 ,0 ,10 ), yval = runif(40 ,0 ,30 ))
21+
22+ # Force equal scaling
23+ p <- ggplot(dat , aes(xval , yval )) + geom_point() + coord_fixed()
24+ # Test
25+ test_that(" coord_fixed() is translated to the right height-width ratio" , {
26+ info <- expect_traces(p , 1 , " force_equal_scaling" )
27+ tr <- info $ traces [[1 ]]
28+ la <- info $ layout
29+ expect_identical(tr $ type , " scatter" )
30+ # height-width ratio check
31+ built <- ggplot_build2(p )
32+ x_range <- range(built [[2 ]]$ ranges [[1 ]]$ x.major_source , na.rm = TRUE )
33+ y_range <- range(built [[2 ]]$ ranges [[1 ]]$ y.major_source , na.rm = TRUE )
34+ yx_ratio <- (y_range [2 ] - y_range [1 ]) / (x_range [2 ] - x_range [1 ])
35+ expect_identical(la $ height / la $ width , yx_ratio * p $ coordinates $ ratio )
36+ })
37+
38+ # Equal scaling, with each 1 on the x axis the same length as y on x axis
39+ p <- ggplot(dat , aes(xval , yval )) + geom_point() + coord_fixed(1 / 3 )
40+ # Test
41+ test_that(" coord_fixed() is translated to the right height-width ratio" , {
42+ info <- expect_traces(p , 1 , " force_equal_scaling" )
43+ tr <- info $ traces [[1 ]]
44+ la <- info $ layout
45+ expect_identical(tr $ type , " scatter" )
46+ # height-width ratio check
47+ built <- ggplot_build2(p )
48+ x_range <- range(built [[2 ]]$ ranges [[1 ]]$ x.major_source , na.rm = TRUE )
49+ y_range <- range(built [[2 ]]$ ranges [[1 ]]$ y.major_source , na.rm = TRUE )
50+ yx_ratio <- (y_range [2 ] - y_range [1 ]) / (x_range [2 ] - x_range [1 ])
51+ expect_identical(la $ height / la $ width , yx_ratio * p $ coordinates $ ratio )
52+ })
0 commit comments