ggplot2 例項-時間序列圖(圖層概念,圖例修改)
阿新 • • 發佈:2019-01-03
近期做時間序列預測,無奈自帶的預測影象太渣太難看。於是用ggplot2自己調整出一張漂亮的圖。
時間序列預測圖,很能體現圖層的概念:
* 因為存在預測區間,先畫線點,會被預測區間覆蓋,所以要注意圖層順序。
* 時間序列圖,使用自帶畫圖背景輸出效果不佳,白色網格效果更好一點。
* 案例一為原始時間序列圖(圖層概念),案例二為優化預測通道後展示圖(圖例修改)
Example1
##整理出兩個畫圖資料,原始資料freq_xts(學習集和檢驗集)以及預測資料##forcastConsequence
ArimaForecastPlot <- function(freq_xts , forcastConsequence){
g <- ggplot()
g <- g + geom_ribbon(aes(ymin=forcastConsequence[,6], ymax=forcastConsequence[,7], x=forcastConsequence[,1]), fill="lightskyblue", alpha=0.2) ##預測區間大
g <- g + geom_ribbon(aes(ymin=forcastConsequence[,4], ymax=forcastConsequence[,5], x=forcastConsequence[,1]), fill="lightskyblue1", alpha=0.3) ##預測區間小
g <- g + geom_line(aes(x=Index, y=freq_xts), data=fortify(freq_xts), col="gray40")
g <- g + geom_point(aes(x=Index, y=freq_xts), data=fortify(freq_xts), col="gray26",size=3,alpha=0.6)
g <- g + geom_line(aes(x=forcastConsequence[,1], y=forcastConsequence[,3]), col="dodgerblue4",size=1)
g <- g + geom_point(aes(x=forcastConsequence[,1], y=forcastConsequence[,3]),col="dodgerblue2",size=3,alpha=0.6)
g <- g + theme(panel.background=element_rect(fill='transparent', color='gray')) ##修改背景
g <- g + labs(x="時間", y="故障數", title="時間序列預測圖")
g
}
ArimaForecastPlot(freq_xts, forcastConsequence)
Example2
ArimaForecastGalleryPlot <- function(freq_xts, forcastGallery){
g <- ggplot()
g <- g + geom_ribbon(aes(ymin=forcastGallery[,3], ymax=forcastGallery[,4], x=forcastGallery[,1]),fill="lightskyblue1", alpha=0.8)
g <- g + geom_line(aes(x=Index, y=freq_xts), data=fortify(freq_xts), col="gray40")
g <- g + geom_point(aes(x=Index, y=freq_xts), data=fortify(freq_xts),size=3,alpha=0.6)
g <- g + geom_point(aes(x=forcastGallery[,1], y=forcastGallery[,2], col=forcastGallery[, 5]))
g <- g + scale_colour_manual(values = c( "tomato", "gray40"), labels=c("錯誤", "正確"), name=" ") ##圖例修改
g <- g + theme(panel.background=element_rect(fill='transparent', color='gray')) ##修改背景
g <- g + labs(x="時間", y="故障數", title="時間序列預測通道圖")
g
}
ArimaForecastGalleryPlot(freq_xts, forcastGallery)