【问题标题】:Plotly R: can't make custom xaxis date ranges to workPlotly R:无法使自定义 xaxis 日期范围起作用
【发布时间】:2016-08-12 13:38:29
【问题描述】:

这应该很简单(我认为),但由于某种原因我无法让它工作。我有这样的数据:

df
           x y
1 2016-08-12 1
2 2016-08-13 2
3 2016-08-14 3
4 2016-08-15 4
5 2016-08-16 5

str(df)
'data.frame':   5 obs. of  2 variables:
 $ x: Date, format: "2016-08-12" "2016-08-13" ...
 $ y: int  1 2 3 4 5

我使用 plotly 如下,但它不会将 xaxis 范围调整为我指定的自定义值。相反,使用数据的范围:

library(plotly)
plot_ly(df, x = x, y = y) %>% layout(xaxis = list(range = c(as.Date('2016-08-01'), as.Date('2016-08-31'))))

另一方面,如果我有这样的数字数据:

df
  x y
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5

并像这样指定一个自定义范围,它工作正常:

plot_ly(df, x = x, y = y) %>% layout(xaxis = list(range = c(-5, 10)))

在使数据范围工作时我缺少什么?

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    引用https://plot.ly/r/reference/#layout-xaxis-range(我加粗):

    range (list) 设置此轴的范围。如果轴type 是 “log”,那么你必须记录你想要的范围的日志(例如设置 范围从 1 到 100,设置范围从 0 到 2)。 如果轴 type 是“日期”,那么您必须将日期转换为 unix 时间 毫秒(自 1970 年 1 月 1 日以来的毫秒数)。为了 例如,要设置从 1970 年 1 月 1 日到 11 月 4 日的日期范围, 2013,设置范围为0到1380844800000.0 每个命名列表有一个 或以下列出的多个键。

    因此,您可以将日期转换为以毫秒为单位的 unix 时间:

    plot_ly(df, x = x, y = y) %>%
        layout(xaxis = list(
            range = 
                c(as.numeric(as.POSIXct("2016-08-01", format="%Y-%m-%d"))*1000,
                  as.numeric(as.POSIXct("2016-08-31", format="%Y-%m-%d"))*1000),
            type = "date"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-11
      • 2020-04-24
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 2020-11-12
      • 2017-01-08
      • 1970-01-01
      相关资源
      最近更新 更多