Is there a way to detect whether axis labels overlap in ggplot2 programmatically?
Suppose I create the following graph:
library(dplyr)
library(tibble)
library(ggplot2)
dt <- mtcars %>% rownames_to_column("name") %>%
dplyr::filter(cyl == 8)
ggplot(dt, aes(x = name, y = mpg)) + geom_point()
I want to programmatically detect whether x-axis labels are overlapping and apply the following first remedy:
ggplot(dt, aes(x = name, y = mpg)) + geom_point() +
scale_x_discrete(guide = guide_axis(n.dodge = 2))
Here is the tricky part. Say the dimensions are different and first remedy also overlaps like this:
I want to apply a second remedy like this:
ggplot(dt, aes(x = name, y = mpg)) + geom_point() +
theme(axis.text.x = element_text(angle=45, hjust = 1, vjust = 1))
Is it possible without visually inspecting the graph?



