Search code examples
rdatetime-seriesbinning

Creating Hexbins with Dates in R hexbin()


I am trying to create hexbins where the x-axis is a date using the hexbin function in the hexbin package in R. When I feed in my data, it seems to convert the dates into a numeric, which gets displayed on the x-axis. I want it force the x-axis to be a date.

#Create Hex Bins
hbin <- hexbin(xData$Date, xData$YAxis, xbins = 80)

#Plot using rBokeh
figure() %>% 
  ly_hexbin(hbin) 

This gives me:

Hexbin Graph


Solution

  • Here's a brute force approach using the underlying grid plotting package. The axes are ugly; maybe someone with better grid skills than I could pretty them up.

    # make some data
    x = seq.Date(as.Date("2015-01-01"),as.Date("2015-12-31"),by='days')
    y = sample(x)
    
    # make the plot and capture the plot
    p <- plot(hexbin(x,y),yaxt='n',xaxt='n')
    
    # calculate the ticks
    x_ticks_date <- 
    x_ticks <- axTicks(1, log = FALSE, usr = as.numeric(range(x)),
                    axp=c(as.numeric(range(x)) ,5))
    class(x_ticks_date) <- 'Date'
    y_ticks_date <- 
    y_ticks <- axTicks(1, log = FALSE, usr = as.numeric(range(y)),
                       axp=c(as.numeric(range(y)) ,5))
    class(y_ticks_date) <- 'Date'
    
    # push the ticks to the view port.
    pushViewport([email protected])
    grid.xaxis(at=x_ticks, label = format(y_ticks_date))
    grid.yaxis(at=y_ticks, label = format(y_ticks_date))