I have an existing ggplot object from which I’ve removed the y title:
library("ggplot")
gg = ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
theme(axis.title.y = element_blank())
Now I want to write a function has_y_title() that tells me if I’ve set the y
title to be element_blank().
has_y_title = function(gg) {
# what code goes here?
# returns TRUE or FALSE
}
The reason I want this is because without it the function below won’t respect
the fact that, for this plot, I don’t want a y title. Instead, it will grab the
column name that was mapped to the y axis, apply format_text to it, and add
it to the plot:
myfunc = function(gg) {
# if (has_y_title(gg)) {
gg$labels$y <- format_text(gg$labels$y)
# }
}
I want to apply format_text only when a y title was intended to be seen. I’ve
tried various things to determine whether element_blank() was used to remove
the y title, but to no avail – I’m sure this info must exist somewhere in the
structure of the ggplot object?
>Solution :
At least for this example, you can use
has_y_title = function(gg) {
!("element_blank" %in% attributes(gg$theme$axis.title.y)$class)
}
I’m not an expert of ggplot internals–there may very well be a more robust or general way.
I found this through poking, I put gg$ in my RStudio console and the auto-complete options included "theme", so I tab-completed that and added a $, gg$theme$ offered "axis.title.y" as the only option. gg$theme$axis.title.y didn’t have any further sub-elements, so I looked at the object and it had "element_blank" in its class attribute.
