在ggplot facets中绘制不同值的垂直线

时间:2016-02-10 18:05:46

标签: r ggplot2

我有这样的数据

> dput(testdat)
structure(list(Type = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Saline", 
"Compound 1"), class = "factor"), Treatment = structure(c(1L, 
2L, 3L, 4L, 6L, 5L), .Label = c(".0032uM", ".016uM", ".08uM", 
".4uM", "2uM", "10uM"), class = "factor"), Peak = c(1071.28430020209, 
1458.23366806524, 2714.49856342393, 3438.83453920159, 3938.86391759534, 
2980.10159109856), Area1 = c(3312.99749863082, 4798.35142770291, 
9044.21362002965, 11241.1497514069, 11575.3444645068, 9521.69011119236
), SS1 = c(781.759834505516, 1191.6273298958, 2180.02082601411, 
2601.33855989239, 2492.11886600804, 2185.39715502702), Conc = c(0.0032, 
0.016, 0.08, 0.4, 10, 2), logconc = c(-2.49485002168009, -1.79588001734408, 
-1.09691001300806, -0.397940008672038, 1, 0.301029995663981), 
    Conc_nm = c(3.2, 16, 80, 400, 10000, 2000), logconc_nm = c(0.505149978319906, 
    1.20411998265592, 1.90308998699194, 2.60205999132796, 4, 
    3.30102999566398)), .Names = c("Type", "Treatment", "Peak", 
"Area1", "SS1", "Conc", "logconc", "Conc_nm", "logconc_nm"), row.names = 2:7, class = "data.frame")

和代码如:

testdat$Conc_nm = as.numeric(gsub("([0-9]+).*$", "\\1", testdat$Treatment))*1000
testdat$logconc_nm = log10(testdat$Conc_nm)
testdatMelt = melt(testdat,id.vars = c('Type','Treatment','Conc','logconc','Conc_nm','logconc_nm'))



val=NULL # EC50
vallog=NULL# logEC50
allDR=NULL
for (i in 3:5){
  currentfit=tryCatch(nls(testdat[,i] ~ SSfpl(logconc_nm,A,B,xmid,scal),dat=testdat),error=function(e) 0)
  if(typeof (currentfit)=='list')
    vallog[i]= summary(currentfit)$coefficients[3]
    val[i]=10^summary(currentfit)$coefficients[3]
}  
vallog=vallog[-c(1:2)]
val=val[-c(1:2)]


ggplot(data = testdatMelt,aes(logconc_nm,value))+
  facet_grid(.~variable)+
  geom_point()+
  scale_x_log10(breaks=round(testdat$logconc_nm,2))+
  geom_smooth(method = 'nls',
              formula = y ~ SSfpl(x,A,B,xmid,scal),se=FALSE)+
  geom_vline(color='red',xintercept = 20,alpha=.5)
  geom_text(aes(x=valog-.225,y=9000,color=variable,label = paste('EC50',val,'nM')))

这会产生3个基于变量的方面,这个方面很好,并且它适合每个方面与它自己的NLS拟合。我的问题是如何在logEC50值(val)处绘制一条垂直线并用EC50(val)注释该线

我的想法是在geom_line()参数中使用for循环,但这不起作用。即     ggplot+geom_line(color='red', xintercept = for (i in 1:3){vallog[i]})。这显然不起作用。还有其他想法吗?

1 个答案:

答案 0 :(得分:2)

通过创建具有适当结构的数据框,可以在 ggplot2 中添加图层。在这种情况下,您需要在每个面板中的不同位置使用垂直线。这意味着您需要一个带有变量的数据框,该变量指示特定行适用于哪个面板,以及相应的拦截:

vert_line_df <- data.frame(variable = c('Peak','Area1','SS1'),
                           vallog = vallog)

然后使用特定数据在图中添加图层:

+ geom_vline(data = vert_line_df,aes(xintercept = vallog),color = "black")