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

How can I create a extension function to a ggplot2 object, with multiple layers, that works with "+"?

For scatter plot’s I usually like to add a identity line.

Code

library(ggplot2)

plot <- 
ggplot(mtcars,aes(qsec,mpg))+
  geom_point()

plot+
  #Identity line
  geom_abline(aes(slope = 1, intercept = 0,alpha = "Identity line"), linetype = "dashed", col = "red")+
  labs(alpha = "")+
  scale_alpha_manual(values = c(1,1))

Output

enter image description here

That works! But since I do this frequently I was thinking about adding as a funtion to my library. I already have some functions there that work with ggplot2.

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

Tentative 1

First I tried to create a function, just like the others I already have:

plt_identity_line <- function(){
  geom_abline(aes(slope = 1, intercept = 0,alpha = "Identity line"), linetype = "dashed")+
    labs(alpha = "")+
    scale_alpha_manual(values = c(1,1))
}

Then, applying to my ggplot object:

plot + plt_identity_line()  

I got the following error:

Error in plt_identity_line(): ! Cannot add ggproto objects together.
Did you forget to add this object to a ggplot object?

I understand that in this case since I am using multiple layers of ggplot and a geometry, the function did not work, since there is no ggplot().

Tentative 2

Considering the error I got before, I succeded with a function like this:

plt_identity_line <- function(ggplot){
  ggplot+
    geom_abline(aes(slope = 1, intercept = 0,alpha = "Identity line"), linetype = "dashed", col = "red")+
    labs(alpha = "")+
    scale_alpha_manual(values = c(1,1))
  
}

plt_identity_line(plot)  

It works! But ideally what I want is a function what I can add to my plot with the operator +.

>Solution :

Put the layers in a list:

plt_identity_line <- function(){
  list(
    geom_abline(aes(slope = 1, intercept = 0, alpha = "Identity line"), 
      linetype = "dashed", color = "red"),
    labs(alpha = ""),
    scale_alpha_manual(values = c(1,1))
  )
}

plot + plt_identity_line()  

enter image description here

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