Minnow
Minnow

Reputation: 1811

Color with plotly in R with datetimes affects x-axis limits

Using plotly in R with datetimes and the color arg, there seems to be an oddity where the x-axis defaults don't work properly. It range spans back to 1970.

library(plotly)

start <- as.POSIXct("2012-01-15")
interval <- 60

end <- start + as.difftime(1, units="days")

mydate <- seq(from=start, by=interval*60, to=end)

mydf <- data.frame(date=mydate, y=rnorm(1:length(mydate)))

p <- plot_ly(data=mydf, x=~date, y=~y, color=~y)
p

enter image description here

Is there a way to fix this or easily hardcode the range?

I've tried using the layout/xaxis arg without success.

plot_ly(data=mydf, x=~date, y=~y, color=~y) %>%
  layout(
    xaxis = list(range = c(1326603600, 1326690000)),
    yaxis = list(range = c(-10, 10)))

Upvotes: 1

Views: 141

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24252

library(plotly)
start <- as.POSIXct("2012-01-15")
interval <- 60
end <- start + as.difftime(1, units="days")
mydate <- seq(from=start, by=interval*60, to=end)
mydf <- data.frame(date=mydate, y=rnorm(1:length(mydate)))

p <- plot_ly(data=mydf, x=~date, y=~y, color=~y, 
             mode="markers", type="scatter", marker=list(size=15)) %>%
add_trace(data=mydf, x=~date, y=~y, mode="lines", line=list(color="navy"))

# Important: set x-axis type as "category" !
p %>% layout(xaxis=list(type="category", range=list(-.5,(length(mydate)-.5))), 
             margin=list(b=100))

enter image description here

Upvotes: 1

Related Questions