Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Programmatically detect if attribute of `theme()` function has been set to `element_blank()` on ggplot2 object

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())

enter image description here

Now I want to write a function has_y_title() that tells me if I’ve set the y
title to be element_blank().

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading