我一直试图创建一个折线图,其中x轴由日期组成,而y是连续变量。现在,x轴标签仅显示年份,但是我想要专门用于2018年7月,2019年7月,...,2022年7月...的标签...我试图使用以下代码指定刻度,但输出不给我我想要的有什么办法可以实现所需的输出?
p <- plot_ly(mode = 'lines', hoverinfo = "x+y")
p <- p %>%
add_trace(name = "Cumulative enrollment", type = "scatter", x = test2$month, y = test2$cumsum, color = I("blue")) %>%
add_lines(x = pred$month, y = pred$cumsum, color = I("red"), linetype = I("dash"), name = 'Projected enrollment \n (19 subjects/month)') %>%
layout(xaxis = list(autotick = F, tickmode = "array", tickvals = c(as.Date('2017-07-01'), as.Date('2018-07-01'), as.Date('2019-07-01'), as.Date('2020-07-01'), as.Date('2021-07-01'), as.Date('2022-07-01'))),
yaxis = list(title = "Number of Subjects (Cumulative)", tickmode = "array", tickvals = c(0, 200, 400, 600, 800, 1000, 1109, 1200)),
shapes = list(hline(1109)),
legend = list(orientation = 'h', xanchor = "center", x = 0.5),
annotations = list(list(
y = 1150,
xref = 'paper',
yref = 'y',
text = 'Required number of subjects',
showarrow = FALSE
)))
p
数据:
> dput(test2)
structure(list(month = structure(c(17348, 17379, 17410, 17440,
17471, 17501, 17532, 17563, 17591, 17622, 17652, 17683, 17713,
17744, 17775, 17805, 17836, 17866, 17897, 17928, 17956, 17987,
18017, 18048, 18078, 18109, 18140, 18170, 18201, 18231, 18262,
18293, 18322, 18353), class = "Date"), count = c(1L, 2L, 13L,
10L, 22L, 11L, 18L, 20L, 24L, 16L, 28L, 18L, 16L, 30L, 18L, 21L,
21L, 21L, 22L, 17L, 24L, 30L, 24L, 17L, 38L, 24L, 23L, 21L, 20L,
10L, 24L, 16L, 17L, 1L), cumsum = c(1L, 3L, 16L, 26L, 48L, 59L,
77L, 97L, 121L, 137L, 165L, 183L, 199L, 229L, 247L, 268L, 289L,
310L, 332L, 349L, 373L, 403L, 427L, 444L, 482L, 506L, 529L, 550L,
570L, 580L, 604L, 620L, 637L, 638L)), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -34L))
> dput(pred)
structure(list(month = structure(c(18383, 18414, 18444, 18475,
18506, 18536, 18567, 18597, 18628, 18659, 18687, 18718, 18748,
18779, 18809, 18840, 18871, 18901, 18932, 18962, 18993, 19024,
19052, 19083, 19113, 19144, 19174, 19205, 19236, 19266, 19297,
19327), class = "Date"), count = c(19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19, 19), cumsum = c(657, 676, 695,
714, 733, 752, 771, 790, 809, 828, 847, 866, 885, 904, 923, 942,
961, 980, 999, 1018, 1037, 1056, 1075, 1094, 1113, 1132, 1151,
1170, 1189, 1208, 1227, 1246)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -32L))
您可以在此处设置自定义值
plot_ly(df, x = x, y = y) %>%
layout(xaxis = list(
range =
c(as.numeric(as.POSIXct("2019-01-01", format="%Y-%m-%d"))*1000,
as.numeric(as.POSIXct("2020-08-31", format="%Y-%m-%d"))*1000),
type = "date"))