代码之家  ›  专栏  ›  技术社区  ›  firmo23

在plotly中为datetime对象设置x轴超过一天

  •  0
  • firmo23  · 技术社区  · 4 年前

    我试图创建一个绘图条形图,x轴显示日期时间,y轴显示值。我看到一个奇怪的x轴,上面的日期比需要的要多得多。正常情况下,我只想要4个有特定日期的酒吧。假设我使用相同的日期,我才能得到预期的结果 "2011-06-04" 对于我所有的价值观。

    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
    

    预期: enter image description here

    鉴于: enter image description here

    0 回复  |  直到 4 年前
        1
  •  1
  •   ismirsehregal    4 年前

    默认情况下,plotly会根据数据的范围创建x轴。最小值和最大值之间的步长是等距的。连续的时间轴——在我看来没有什么“奇怪”的(数字数据也是如此)。

    但是,如果您更想按类别查看数据,可以使用 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