将数据点添加到现有散点图

时间:2013-03-01 13:20:55

标签: r ggplot2

我有一个现有的ggplot2散点图,它显示了来自普通数据库的参数结果。然后我想在此图中添加两个额外的点,我将其作为命令行参数传递给我的脚本script age value1 value2。我想将这些点显示为红色,每个点上方都有一个r和l geom_text。到目前为止,我有以下代码,但不知道如何添加最后的润色

pkgLoad <- function(x)
  {
    if (!require(x,character.only = TRUE))
    {
      install.packages(x,dep=TRUE, repos='http://star-www.st-andrews.ac.uk/cran/')
      if(!require(x,character.only = TRUE)) stop("Package not found")
    }

  }

pkgLoad("ggplot2")
#load current normals database
df<-data.frame(read.csv("dat_normals.txt", sep='\t', header=T))

args<-commandArgs(TRUE)

#specify what each argument is
age <- args[1]
rSBR <- args[2]
lSBR <- args[3]

# RUN REGRESSION AND APPEND PREDICTION INTERVALS
lm_fit = lm(SBR ~ Age, data = df)
sbr_with_pred = data.frame(df, predict(lm_fit, interval='prediction'))




p <- ggplot(sbr_with_pred, aes(x=Age, y=SBR)) + 
          geom_point(shape=19, alpha=1/4) +
          geom_smooth(method = 'lm', aes(fill = 'confidence'), alpha = 0.5) +
          geom_ribbon(aes(y = fit, ymin = lwr, ymax = upr, 
                         fill = 'prediction'), alpha = 0.2) + 
          scale_fill_manual('Interval', values = c('green', 'blue')) +
          theme_bw() + 
          theme(legend.position = "none") 


ggsave(filename=paste("/home/data/wolf/FV_DAT/dat_results.png",sep=""))
browseURL(paste("/home/data/wolf/FV_DAT/dat_results.png",sep""))

基本上,我想看看2个新点是否在普通数据库的95%置信区间内(蓝丝带)enter image description here

1 个答案:

答案 0 :(得分:2)

您的示例无法重现。创建数据和可重复的示例确实很有建设性。这不是浪费时间。对于解决方案,我会在评论中写下它的内容。您添加一个包含新数据的新图层。

  newdata <- data.frame(Age = args[1],
                        SBR = c(args[2],args[3]))
  p + geom_point(data=newdata,colour="red",size=10)

例如:

sbr_with_pred&lt; - data.frame(Age = sample(15:36,50,rep = T),                             SBR = rnorm(50))

p <- ggplot(sbr_with_pred, aes(x=Age, y=SBR)) + 
  geom_point(shape=19, alpha=1/4) +
  geom_smooth(method = 'lm', aes(fill = 'confidence'), alpha = 0.5) 

  args <- c(20,rnorm(1),rnorm(2))
  newdata <- data.frame(Age = args[1],
                        SBR = c(args[2],args[3]))
  p + geom_point(data=newdata,colour="red",size=10)

enter image description here