gpt4 book ai didi

r - plotly R : can't make custom xaxis date ranges to work

转载 作者:行者123 更新时间:2023-12-02 20:59:46 25 4
gpt4 key购买 nike

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

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

我按如下方式使用绘图,但它不会将 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)))

在使数据范围发挥作用时我缺少什么?

最佳答案

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

range (list) Sets the range of this axis. If the axis type is "log", then you must take the log of your desired range (e.g. to set the range from 1 to 100, set the range from 0 to 2). If the axis type is "date", then you must convert the date to unix time in milliseconds (the number of milliseconds since January 1st, 1970). For example, to set the date range from January 1st 1970 to November 4th, 2013, set the range from 0 to 1380844800000.0 Each named list has one or more of the keys listed below.

因此,您可以将日期转换为以毫秒为单位的 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"))

关于r - plotly R : can't make custom xaxis date ranges to work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38919395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com