查询主题的答案并不可靠,因为无论主题设置如何,情节都可以具有固定的纵横比,仅仅是因为坐标使它如此。例如,任何基于geom_sf() 的绘图都将具有固定的纵横比。正确的做法是查询 ggplot 生成的 grob。
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