在R中以plot方式在同一绘图中绘制静态和动画折线图

时间:2018-09-13 09:17:03

标签: r plot plotly r-plotly timeserieschart

我的目的是在相同的绘图区域中创建2个折线图,但是1个应该是静态的(始终显示),而另一个动画的(只要用户单击“播放”按钮就可以立即显示)提供)。概念是我们有一个始终显示实际值的折线图,而动画的将是拟合的观测值,显示它们与实际线的拟合程度。

到目前为止,我已经实现了以动画方式创建两条线,但是,如前所述,我希望将Type=="Actuals"的观测值设为静态,而将其他观测值(Type=="Fitted")设为动画。请在下面参考我当前的脚本。

初始工作数据框为data2,它将实际值和拟合值保持统一;列为RequCreatedFull-Date(as POSIXct), Requs_Qnt_pm(as num), Type(as Factor-indicates whether the record refers to 'actual' or 'fitted' observation), date(as num),其中
 date=(year(RequCreatedFull_Date)+(month(RequCreatedFull_Date)-1)/12)

library(plotly)
library(dplyr)
library(lubridate)

#function definition for to be framed variable manipulation
accumulate_by <- function(dat, var) {
  var <- lazyeval::f_eval(var, dat)
  lvls <- plotly:::getLevels(var)
  dats <- lapply(seq_along(lvls), function(x) {
   cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
  })
  dplyr::bind_rows(dats)
}

#creation of to-be-used for framing variable
data2mod <- data2 %>%
  accumulate_by(~date)


#graph creation
my_graph<-data2mod %>%
             plot_ly(
               x = ~date, 
               y = ~Requs_Qnt_pm,
               split = ~Type,
               frame = ~frame,
               type = 'scatter',
               mode = 'lines', 
               line = list(simplyfy = F)
            ) %>% 
             layout(
                xaxis = list(
                  title = "x axis title",
                  zeroline = F
               ),
                yaxis = list(
                  title = "y axis title",
                  zeroline = F
               )
            ) %>% 
            animation_opts(
              frame = 100, 
              transition = 0, 
              redraw = FALSE
            ) %>%
            animation_slider(
              hide = T
            ) %>%
            animation_button(
               x = 1, xanchor = "right", y = 0, yanchor = "bottom"
            )

更新: data2

#preparing 2 data tables for the plot (got to be merged with new Type var indicating actuals and fit observations)
agg_acts_rags_rf_ama2<-data.frame(agg_acts_rags_rf_ama, Type="Actuals", date=year(agg_acts_rags_rf_ama$RequCreatedFull_Date)+(month(agg_acts_rags_rf_ama$RequCreatedFull_Date)-1)/12)
agg_fits_rags_rf_ama2<-data.frame(agg_fits_rags_rf_ama, Type="Fitted", date=year(agg_fits_rags_rf_ama$RequCreatedFull_Date)+(month(agg_fits_rags_rf_ama$RequCreatedFull_Date)-1)/12)

names(agg_acts_rags_rf_ama2)[2]<-"Requs_Qnt_pm"
names(agg_fits_rags_rf_ama2)[2]<-"Requs_Qnt_pm"

#unifying the tables
data2<-rbind(agg_acts_rags_rf_ama2, agg_fits_rags_rf_ama2)

agg_acts_rags_rf_amaagg_fits_rags_rf_ama仅包含2列,RequCreatedFull_Date和数量列

0 个答案:

没有答案