2017-02-16 94 views
0

我在計數數據上運行泊松廣義線性模型,並使用ggplot繪製數據和擬合模型。ggplot2和geom_ribbon:eval(expr,envir,enclos)中的錯誤:未找到對象'Freq'

我的數據:

structure(list(YR = c(1960, 1961, 1962, 1963, 1964, 1965, 1966, 
1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 
1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 
1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 
2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 
2011, 2012, 2013, 2014, 2015, 2016), Freq = c(0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 
0L, 0L, 2L, 0L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 4L, 1L, 2L, 4L, 5L, 
3L, 2L, 5L, 2L, 14L, 6L, 5L, 5L, 10L, 13L, 10L, 5L, 8L, 7L, 6L, 
10L, 12L, 14L, 2L, 16L, 15L)), .Names = c("YR", "Freq"), row.names = 58:114, class = "data.frame") 

這裏的劇本,第一個模型,參數和陰謀使用geom_ribbon:

mod <- glm(Freq~YR, data = sub9, family = "poisson") 

pred.df <- data.frame(YR = seq(min(sub9$YR), max(sub9$YR), length.out = 100)) 
pred <- predict(mod, newdata = pred.df, se.fit = TRUE) 
pred.df$count <- exp(pred$fit) 
pred.df$countmin <- exp(pred$fit - 2 * pred$se.fit) 
pred.df$countmax <- exp(pred$fit + 2 * pred$se.fit) 

ggplot(sub9,aes(x=YR,y=Freq)) + 
    scale_y_continuous(limits=c(0,75),breaks=c(10,20,30,40,50,60,70),expand=c(0,0)) + 
    scale_x_continuous(limits=c(1960,2018),breaks=c(1960,1965,1970, 
               1975,1980,1985,1990,1995, 
               2000,2005,2010,2015)) + 
    geom_point() + 
    geom_ribbon(data = pred.df, aes(ymin = countmin, ymax = countmax), alpha=0.3) + 
    geom_line(data = pred.df) + 
    xlab(" ") + ylab("Count") 

先有成功的一個數據集運行這個程序後,我使用新的和類似的數據集嘗試相同的過程時會收到錯誤消息。錯誤消息:

Error in eval(expr, envir, enclos) : object 'Freq' not found 

我已經做的唯一事情是替換數據幀的名稱,並從「計數」爲「頻率」改變了因變量的名稱,根據數據幀。我究竟做錯了什麼?

回答

1

這應該工作(需要在aes指定ycount):

ggplot(sub9,aes(x=YR,y=Freq)) + 
    scale_y_continuous(limits=c(0,75),breaks=c(10,20,30,40,50,60,70),expand=c(0,0)) + 
    scale_x_continuous(limits=c(1960,2018),breaks=c(1960,1965,1970, 
                1975,1980,1985,1990,1995, 
                2000,2005,2010,2015)) + 
    geom_point() + 
    geom_ribbon(data = pred.df, aes(y=count, ymin = countmin, ymax = countmax), alpha=0.3) + 
    geom_line(data = pred.df,aes(x=YR,y=count)) + 
    xlab(" ") + ylab("Count") 

enter image description here

0

問題是你有DF和pred.df衝突。使用ggplot()可以給你想要的東西:

ggplot() + geom_point(data=df,aes(x=YR,y=Freq)) + geom_ribbon(data = pred.df, aes(x=YR,ymin = countmin, ymax = countmax)) + geom_line(data = pred.df, aes(x=YR,y= count))+ xlab(" ") + ylab("Count")+scale_y_continuous(limits=c(0,75),breaks=c(10,20,30,40,50,60,70),expand=c(0,0)) +scale_x_continuous(limits=c(1960,2018),breaks=c(1960,1965,1970,1975,1980,1985,1990,1995,2000,2005,2010,2015)) 

enter image description here

相關問題