I want to write a ggplot2 theme, that formats the x-Axis differently when the x-Axis contains numerical values or factors.
Is it possible to detect which type of scale is used from within the theme call? If yes, how?
My code would look something like this, im looking for an expression to replace the pseucodode in the angle brackets:
my_theme <- function(){
thm <- theme_bw() %+replace%
theme(
panel.border = element_blank()
)
if(<x-Axis scale is factor?>){
thm <- thm %+replace%
axis.ticks.x = element_blank()
}
thm
}
layer_scales
is a helper function in ggplot2 that returns the scale associated with a layer (by default the first geom layer) of your plot, so something like class(layer_scales(plot)$x)
can tell you the type of x-axis you are dealing with.
Here's an example for how it can be implemented:
# continuous x-axis plot (the additional specifications are there to make sure
# its look closely matches the next one
p1 <- ggplot(mtcars, aes(gear, wt, colour = factor(cyl))) +
geom_point(size = 4, show.legend = FALSE) +
scale_x_continuous(breaks = c(3, 4, 5),
expand = c(0, 0.6))
# discrete x-axis plot
p2 <- ggplot(mtcars, aes(factor(gear), wt, colour = factor(cyl))) +
geom_point(size = 4, show.legend = FALSE)
my_theme <- function(plot){
thm <- theme_bw() %+replace%
theme(
panel.border = element_blank()
)
if("ScaleDiscrete" %in% class(layer_scales(plot)$x)){
thm <- thm %+replace%
theme(
axis.ticks.x = element_blank()
)
}
plot + thm
}
# check the difference in results for p1 & p2. p1 has axis ticks while p2 does not.
gridExtra::grid.arrange(my_theme(p1), my_theme(p2), nrow = 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With