Search code examples
rrcharts

hPlot R x-axis label and x-y correspondence


I have the following data and trying to plot using hPlot

hPlot(Numbers~Date, data = df, group='Type', type = "line", radius=6)


     Date        Type      Numbers
 2014-01-05     Type-1          16
 2014-01-12     Type-1          82
 2014-01-12     Type-2           2
 2014-01-19     Type-1         177
 2014-01-26     Type-1         270
 2014-01-26     Type-2           3
 2014-02-02     Type-1         381
 2014-02-09     Type-1         461
 2014-02-09     Type-2           4

I am getting multiple dates as x-axis as shown in figure below. I also tried unique and as.character but the x-data is not corresponding to y-data.

enter image description here


Solution

  • Here is the solution to your problem. You can view the chart along with code here. I am posting it here as well

    # don't switch to scientific notation, since we want date to be
    # represented in milliseconds
    options(scipen = 13)
    dat = transform(df, Date2 = as.numeric(as.POSIXct(Date))*1000)
    
    library(rCharts)
    h1 <- hPlot(Numbers ~ Date2, data = dat, 
      group = 'Type', 
      type = "line", 
      radius=6
    )
    h1$xAxis(type = 'datetime', labels = list(
      format = '{value:%Y-%m-%d}'  
    ))
    h1