Facebook的Prophet in R(还有Python版本)用于生成时间序列预测。
模型m
由以下人员创建:
m <- prophet(df)
future <- make_future_dataframe(m, periods = 365)
forecast <- predict(m, future)
plot(m, forecast)
哪个会返回格式很好的图形,例如:
我想更改线型,而不是点,而是通常的细线。
我尝试过
lines(m$history$y,lty=1)
但出现错误
In doTryCatch(return(expr), name, parentenv, handler)
是否有任何建议将这些点转换为线?
答案 0 :(得分:2)
用于_tkinter.TclError: Layout PViewStyle not found
对象的plot
方法使用prophet
,因此像ggplot2
这样的基本R图形功能将不起作用。您可以使用lines()
来添加线,但是目前我看不到一种简单的方法来逐行替换点...
ggplot2::geom_line()
中的示例:
?prophet
添加行:
history <- data.frame(ds = seq(as.Date('2015-01-01'), as.Date('2016-01-01'), by = 'd'),
y = sin(1:366/200) + rnorm(366)/10)
m <- prophet(history)
future <- make_future_dataframe(m, periods = 365)
forecast <- predict(m, future)
pp <- plot(m,forecast)
This question提供了一种(hacky)前进的方式:
library(ggplot2)
pp + geom_line()
但是很明显,hack出了点问题。最好的选择是查看plot方法(pp2 <- pp + geom_line()
qq2 <- ggplot_build(pp2)
qq2$data[[2]]$colour <- NA
plot(ggplot_gtable(qq2))
)并对其进行修改以使其表现出所需的行为……这是基本版本:
prophet:::plot.prophet
尽管...我可能已经去除了您的数据/预测中存在的某些组件。
答案 1 :(得分:1)
在此之前,可以使用dyplot.prophet(m, forecast)
(plot的html版本)进行这样的操作:),我们应该像下面这样重写函数:
dyplot.prophet <- function(x, fcst, uncertainty=TRUE,
...)
{
forecast.label='Predicted'
actual.label='Actual'
# create data.frame for plotting
df <- prophet:::df_for_plotting(x, fcst)
# build variables to include, or not, the uncertainty data
if(uncertainty && exists("yhat_lower", where = df))
{
colsToKeep <- c('y', 'yhat', 'yhat_lower', 'yhat_upper')
forecastCols <- c('yhat_lower', 'yhat', 'yhat_upper')
} else
{
colsToKeep <- c('y', 'yhat')
forecastCols <- c('yhat')
}
# convert to xts for easier date handling by dygraph
dfTS <- xts::xts(df %>% dplyr::select_(.dots=colsToKeep), order.by = df$ds)
# base plot
dyBase <- dygraphs::dygraph(dfTS)
presAnnotation <- function(dygraph, x, text) {
dygraph %>%
dygraphs::dyAnnotation(x, text, text, attachAtBottom = TRUE)
}
dyBase <- dyBase %>%
# plot actual values
dygraphs::dySeries(
'y', label=actual.label, color='black',stepPlot = TRUE, strokeWidth=1
) %>%
# plot forecast and ribbon
dygraphs::dySeries(forecastCols, label=forecast.label, color='blue') %>%
# allow zooming
dygraphs::dyRangeSelector() %>%
# make unzoom button
dygraphs::dyUnzoom()
if (!is.null(x$holidays)) {
for (i in 1:nrow(x$holidays)) {
# make a gray line
dyBase <- dyBase %>% dygraphs::dyEvent(
x$holidays$ds[i],color = "rgb(200,200,200)", strokePattern = "solid")
dyBase <- dyBase %>% dygraphs::dyAnnotation(
x$holidays$ds[i], x$holidays$holiday[i], x$holidays$holiday[i],
attachAtBottom = TRUE)
}
}
return(dyBase)
}
strokeWidth=0
是以前的版本,我们将其更改为strokeWidth=1
,并添加了stepPlot = TRUE
整个基本代码位于此处:https://rdrr.io/cran/prophet/src/R/plot.R