3

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.

Muon
  • 1,294
  • 1
  • 9
  • 31

2 Answers2

1

The problem was that they x were not having sufficient significance to be differentiated by milliseconds.

library(plotly)

# make some data
x <- seq(1, 10, by=.25)
y <- 1:length(x)

# convert to POSIX
x <- as.POSIXct(x, origin='1970-01-01')
# show milisecond format

x <- format(x, "%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')

enter image description here

Mohanasundaram
  • 2,889
  • 1
  • 8
  • 18
  • Thanks very much for your input Mohanasundaram. However, the values themselves are still rounded. I'm trying to remove the "step" pattern you see in the plot. In this plot, I would want to see a straight linear line. Does that make sense? I have updated the question to make this more clear. – Muon Apr 25 '20 at 04:21
  • 1
    Thanks again @Mohanasundaram. This is a good workaround but still not exactly what I am after because this is just converting `x` to a character class and consequently we lose out on using Plotly's dynamic formatting of datetimes (i.e. shows date once followed by timestamps). I have updated the question again. – Muon Apr 25 '20 at 05:14
1

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!

Bastian
  • 620
  • 5
  • 14
  • Setting `options("digits.secs"=6)` works. Thanks! Seems to work fine without changing the Plotly xaxis layout. – Muon Aug 12 '20 at 07:40