将函数传递给 ggplot 密度图
Passing a function to the ggplot density plot
我有三个 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_id
和 BF
值。
这是我试过的,
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()
}}
如果有人能告诉我如何将搜索字符串传递给矩阵,然后将结果输入 annotate
的 ggplot geom_label
以根据位置标记它,那就太好了它位于密度图中。任何帮助将不胜感激。
已编辑:
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")
我有三个 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_id
和 BF
值。
这是我试过的,
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()
}}
如果有人能告诉我如何将搜索字符串传递给矩阵,然后将结果输入 annotate
的 ggplot geom_label
以根据位置标记它,那就太好了它位于密度图中。任何帮助将不胜感激。
已编辑:
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")