首页 > 解决方案 > 将函数传递给 ggplot 密度图

问题描述

我有三个 data.frames 和一个字符串作为函数的输入,我需要函数在其中一个数据帧中搜索字符串并在密度图中标记相应的值。bg0 和 bg1 有一列 x 和 ,我用它来绘制密度图。

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

例如,如果搜索字符串是 AA,那么程序必须在matrix数据框中搜索它并在密度图上标记它的值sample_idBF

这是我尝试过的,

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

如果有人可以指导我如何将搜索字符串传递给矩阵,然后将结果输入 ggplot以根据它在密度图中的位置对其进行标记,那就太好geom_label了。annotate任何帮助,将不胜感激。

标签: rggplot2labeldensity-plot

解决方案


编辑:

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

在此处输入图像描述


推荐阅读