Home > Enterprise >  How can I create a extension function to a ggplot2 object, with multiple layers, that works with &qu
How can I create a extension function to a ggplot2 object, with multiple layers, that works with &qu

Time:01-12

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.

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 .

CodePudding user response:

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

  • Related