2016-12-04 90 views
1

所以我有以下的数据集 -与R中重复的x值绘制

dat <- structure(list(cases = c(2L, 6L, 10L, 8L, 12L, 9L, 28L, 28L, 
36L, 32L, 46L, 47L), qrt = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 
1L, 2L, 3L, 4L), date = c(83, 83.25, 83.5, 83.75, 84, 84.25, 
84.5, 84.75, 85, 85.25, 85.5, 85.75)), .Names = c("cases", "qrt", 
"date"), class = "data.frame", row.names = c(NA, -12L)) 


    cases qrt date 
    2 1  83.00 
    6 2  83.25 
    10 3  83.50 
    8 4  83.75 
    12 1  84.00 
    9 2  84.25 
    28 3  84.50 
    28 4  84.75 
    36 1  85.00 
    32 2  85.25 
    46 3  85.50 
    47 4  85.75 

有更多的数据点,反而使事情看起来简单一点我忽略他们。

而且这个数据集我有适合GLM:

fit <- glm(cases~date+qrt, family = poisson, data = dat) 

基本上,我想创造这个GLM产生,看起来像这样这个拟合值的曲线(这实际上是为剧情完整的数据集,黑圆圈是原始数据和空圈是拟合数据)

enter image description here

与QRT在x axis.I'm假设我不得不重复x值使用predict()功能离子,然后绘制结果值,但我已经尝试过这一点,我得到X轴上的X值从1到12,而不是重复1,2,3,4,1,2,3,4等。另外,如何绘制拟合值的原始数据,如上图所示?

+0

不幸的是,我没有代码,我只知道,它的意思是看起来像图像中的情节。 – tattybojangler

回答

1

这并不困难。只需使用axis控制轴显示:

## disable "x-axis" when `plot` fitted values 
## remember to set decent `ylim` for your plot 
plot(fit$fitted, xaxt = "n", xlab = "qtr", ylab = "cases", main = "GLM", 
    ylim = range(c(fit$fitted, dat$cases))) 
## manually add "x-axis", with "labels" and "las" 
axis(1, at = 1:12, labels = rep.int(1:4, 3), las = 2) 
## add original observed cases 
points(dat$cases, pch = 19) 

plot

你不需要在这里使用predict。您的季度时间系列中没有缺口/缺失值,因此您所需的所有内置拟合值都适用于fit

0

与ggplot:

df <- rbind(data.frame(index=as.factor(1:nrow(dat)), value=dat$cases, cases='actual'), 
      data.frame(index=as.factor(1:nrow(dat)), value=predict(fit, type='response'), cases='predicted')) 
library(ggplot2) 
ggplot(df, aes(index, value, color=cases)) + geom_point(cex=3) + 
    scale_color_manual(values=c('black', 'gray')) + 
    scale_y_continuous(breaks=seq(0, max(df$value)+5, 5)) + theme_bw() 

enter image description here