Interactive plot with dygraphs in R

   Dygraphs is an open source JavaScript charting library. You may find more information about it on this link. This post is about a simple usage of the dygraphs function to plot interactive charts. R dygraphs package provides an interactive plotting interface with dygraphs JavaScript library. It is an easy and useful graph plotting tool for time series data. Information about R dygraphs library is in here.
   First, we'll start with installing dygraphs package.

> install.packages("dygraphs")
> library(dygraphs)

Next, we'll generate sample dataset to plot.

> value<-sample(100:800,100,replace = T)
> time<-seq(from=Sys.time(),to=Sys.time()+60*60*24*99,by="day")
> df<-data.frame(time=time,value=value)

Data should be converted to extensible time-series type. The data frame can not be used directly with dygraph function.

> dygraph(df)
Error in dygraph(df) : Unsupported type passed to argument 'data'.

  Thus, we need to convert our data frame into xts type object. A zoo and xts libraries help us to convert data frame. You may need to install them if they are not available in your machine.

> library(zoo)
> library(xts)

 Converting df_data to xts type as below.

> dy_data<-df %>% read.zoo() %>% as.xts()

Now, we can plot dy_data with dygraph function.

> dygraph(dy_data)
 


   We can add some options.

> dygraph(dy_data) 
       %>% dyOptions(colors="red", pointSize = 2,drawGrid =T,stepPlot = T) 
       %>% dyRangeSelector()





Range selector is a convenient feature to check any area of plot series.
In this post, we have learned a simple usage of dygraphs to plot data. Thank you for reading!

No comments:

Post a Comment