ggplot2 和 geom_ribbon: eval(expr, envir, enclos) 错误:找不到对象 'Freq'

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

我运行在我的计数数据上建立泊松广义线性模型,并使用 ggplot 绘制数据和拟合模型。

我的数据:

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

我唯一做的就是根据数据框替换数据框的名称并将因变量的名称从"count"更改为"Freq"。我做错了什么?

这应该有效(您需要在 aes 中将 y 指定为 count):

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")

问题是你有 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))