Ответы, которые запрашивают тему, ненадежны, потому что график может иметь фиксированное соотношение сторон просто потому, что его делает координата, независимо от настроек темы. Например, любые графики, основанные на geom_sf()
, будут иметь фиксированное соотношение сторон. Правильный способ сделать это - запросить гроб, сгенерированный ggplot.
library(tidyverse)
p_var <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point()
p_fixed <- p_var + coord_fixed()
# correct approach: query the grob
is_fixed_ratio <- function(plot) {
g <- ggplotGrob(plot)
isTRUE(g$respect)
}
# should return false
is_fixed_ratio(p_var)
#> [1] FALSE
# should return true
is_fixed_ratio(p_fixed)
#> [1] TRUE
В отличие от этого, если мы используем неправильный подход, все работает не так, как ожидалось.
# incorrect approach: rely on a theme setting
is_fixed_ratio_wrong <- function(plot) {
purrr::map(plot, "aspect.ratio") %>%
unlist() %>%
is.null() %>%
!.
}
# should return false, and does so
is_fixed_ratio_wrong(p_var)
#> [1] FALSE
# should return true, but doesn't
is_fixed_ratio_wrong(p_fixed)
#> [1] FALSE
Это работает также для примера, приведенного в вопросе:
plot_a <- ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
geom_point()+
theme(aspect.ratio = 1)
plot_b <- ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
geom_point()
is_fixed_ratio(plot_a)
#> [1] TRUE
is_fixed_ratio(plot_b)
#> [1] FALSE
Еще один пример:
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
p <- ggplot(nc) +
geom_sf(aes(fill = AREA))
is_fixed_ratio(p)
#> [1] TRUE
is_fixed_ratio_wrong(p)
#> [1] FALSE