Search code examples
rplotlyposixct

Plot timestamps showing milliseconds with Plotly in R


I'm trying to plot a time series with Plotly which includes milliseconds. However, Plotly rounds each timestamp to the nearest second when displaying the data. I would like the data to be plotted so that the points are evenly spaced along the x-axis so I don't get this "step" pattern you see in the below plot.

library(plotly)

# make some data
x <- seq(1, 10000, by=250)/1000
y <- 1:length(x)

# convert to POSIX
x <- as.POSIXct(x, origin='1970-01-01', tz='UTC')
# show milisecond format
format(x[1:5], "%Y-%m-%d %H:%M:%OS3")

# make data frame
data <- data.frame(x, y)

# make the plot with plotly
plot_ly(data, x=~x, y=~y, type='scatter', mode='lines+markers')

Plotly Example

I tried changing the x-axis ticks to display milliseconds but this did not work for me.

layout(xaxis = list(tickformat="%H:%M:%OS3"))

Edit: Mohanasundaram answer is a good workaround but I am looking for a way to achieve this while maintaining the "POSIXct" and "POSIXt" classes.


Solution

  • I had a similar issue. I found that adding options("digits.secs"=6) to my script, before calling plotly, made plotly aware of the milliseconds present in my POSIXct timestamps.

    I formatted the timestamps with:

    df$Timestamp = as.POSIXct(D_blinks$Timestamp, format = "%Y-%m-%d %H:%M:%OS")
    

    and asked plotly to display the milliseconds using:

    layout( xaxis = list(tickformat="%H:%M:%S.%L ms") )
    

    I hope it helps someone!