2016-12-04 162 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