Set x-axis for datetime object for more than one days in plotly

Viewed 104

Im trying to create a plotly bar chart with datetime in x-axis and values on y-axis. Im getting a weird x-axis in which I see much more dates than needed. Normaly I would like to have only 4 bars with specific datetimes. I get the expected result only if I use the same date ,lets say "2011-06-04" for all my values.

library(plotly)
datetime<-c("2011-06-04 12:00:00","2011-06-04 14:00:00","2011-06-04 15:00:00","2011-07-04 18:00:00")
name<-c(5,10,15,20)
SAMPLE<-data.frame(datetime,name)
SAMPLE$datetime<-as.POSIXct(SAMPLE$datetime,format="%Y-%m-%d %H:%M:%S")

fig <- plot_ly(SAMPLE, x = ~datetime, y = ~name, type = 'bar',
               marker = list(color = 'rgb(158,202,225)',
                             line = list(color = 'rgb(8,48,107)',
                                         width = 1.5)))

fig

Expected: enter image description here

Given: enter image description here

1 Answers

plotly by default creates the x-axis based on the range of your data. The steps between min and max are equidistant. Continuous time axis - nothing "weird" here in my eyes (it does the same for numeric data).

However, if you rather want to view the data in categories you can use factor():

library(plotly)
datetime<-c("2011-06-04 12:00:00","2011-06-04 14:00:00","2011-06-04 15:00:00","2011-07-04 18:00:00")
name<-c(5,10,15,20)
SAMPLE<-data.frame(datetime,name)
SAMPLE$datetime<-as.POSIXct(SAMPLE$datetime,format="%Y-%m-%d %H:%M:%S")

fig <- plot_ly(SAMPLE, x = ~factor(datetime), y = ~name, type = 'bar',
               marker = list(color = 'rgb(158,202,225)',
                             line = list(color = 'rgb(8,48,107)',
                                         width = 1.5)))

fig

result

Related