r - 将函数传递给 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_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()
}}
如果有人可以指导我如何将搜索字符串传递给矩阵,然后将结果输入 ggplot以根据它在密度图中的位置对其进行标记,那就太好geom_label
了。annotate
任何帮助,将不胜感激。
解决方案
编辑:
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")
推荐阅读
- javascript - 如何在课堂上进行全局解构?
- azure - 使用 Application Insights 监视 IIS 应用程序
- mongodb - 如何使用当前时间和文档中的另一个字段创建 mongodb 查询?
- java - 使用 eclipse 生成 .jar 文件后如何加载图像?
- sql-server - 从 SSMS 2008 迁移到 SSMS 2016 后,数据库服务器面临缓慢的问题
- html -
- 如何将导航栏中的最后一项设置在右侧
- kubernetes-ingress - 通过使用 Istio 端点身份验证,使用 Firebase 对 JWT 进行身份验证
- clips - CLIPS 无法识别 deftemplate 名称
- javascript - 我没有在素数函数中得到平方循环索引
- php - 发送邮件后重定向不起作用 | Laravel