Search code examples
rggplot2labeldensity-plot

Passing a function to the ggplot density plot


I have three data.frames and a string as inputs to my function, I need the function search for the string in one of the dataframe and label the corresponding values in the density plot. The bg0, and bg1 has one column x and and which I used to plot the density plots.

bg0 = data.frame(x = c(1.2, 2.567, 0.9188, 0.52623))
bg1 = data.frame(x = c(7.98, 9.867, 4.678, 2.877))
matrix = data.frame(sample_id = c(AA, BB, CC, FF, EE),
                    BF = c(1.2, 2.567, 5.98, 7.098, 10.987))

For example, if search string is AA then the program must search it in matrix data frame and label its sample_id and BF value on the density plot.

Here is what I tried,

plotter <- function(bg0, bg1, matrix, string){
  if (string %in% matrix$sample_id) {
    p1 = ggplot(data = bg0, aes(x=x,fill = "blue")) + 
      geom_density(alpha = .3) + 
      geom_density(data = bg1, aes(x=x,fill = "green")) + 
      geom_label(label=sprintf('n = %s', matrix$sample_id))
    pdf(outfile, width=50, height=20)
    print(p1)
    dev.off() 
  }}

It would be great if someone can walk me through with how to pass the search string to a matrix and then feeding the results into the ggplot geom_label of annotate to label it based on where it is located in the density graph. Any help would be appreciated.


Solution

  • Edited:

    plotter <- function(bg0, bg1, matrix, string){
                      if (nrow(matrix[which(matrix$sample_id==string),])!=0) {
                       mylabel = paste('BF = ',matrix[which(matrix$sample_id==string),]$BF,sep=" ")
                       p1 = ggplot(data = bg0, aes(x=x,fill = "blue") )+ 
                       geom_density(alpha = .3) + 
                       geom_density(data = bg1, aes(x=x,fill = "green"))+
                       geom_vline(xintercept = matrix[which(matrix$sample_id==string),]$BF, 
                       linetype="dotted", color = "blue", size=1.5)+
                       geom_text(aes(x=matrix[which(matrix$sample_id==string),]$BF, 
                       label=mylabel, y=.6), colour="blue",hjust = -0.5) 
                      #pdf(outfile, width=50, height=20)
                      return(print(p1))
                      dev.off() 
                      }
                 }
      plotter(bg0, bg1, matrix, "BB")
    

    enter image description here