如何在 plotly 中设置自定义日期 ticks/breaks

How to set custom date ticks/breaks in plotly

我正在尝试为 x 轴上的特定日期设置自定义刻度。 到目前为止我已经尝试过:

我越接近我想要的是使用下面显示的代码。但是,我需要的第一个刻度不会显示(我想用作 breaks/ticks 的日期可以在 rangebreaks 中找到):

    df <- tibble(
  name = c("pat", "bill", "chuck", "dick", "ted"),
  uni = factor(c("DM", "DM", "DM", "VM", "VM")),
  cond =factor(c( "D", "E", "D", "E", "D")),
  f_des = as.Date(c( "2021-07-28", "2021-11-05", "2022-02-02", "2021-07-30", "2022-03-10")),
  f_ces = as.Date(c( "2021-11-04", "2022-01-15", "2022-04-10", "2022-03-10", "2022-04-10"))
)

#plot
ggplot(df, aes(fill = cond, text = name)) + 
  geom_rect(aes( xmin = f_des, xmax = f_ces,
                 ymin = as.numeric(uni) - .6 / 2, ymax = as.numeric(uni) + width / 2)) +
  scale_y_continuous(breaks = seq(levels(df$uni)), labels = levels(df$uni), expand = c(0.01,0))

ggplotly(tooltip = c("text")) %>%
  layout(xaxis = list( 
    rangebreaks = list(values= c( "2021-07-30","2021-10-07","2021-11-05","2022-02-02")),
                       tickcolor="crimson", gridcolor="crimson"))

这是输出: plot screenshot with less ticks/grids than expected

可能有更直接的选择,但一个选择是首先定义您想要的日期间隔并将它们转换为适当的 Date 对象。

对于 tickvals 将分隔符转换为数字,对于 ticktext 格式,分隔符为您想要的格式:

library(plotly)

width <- .9

breaks <- as.Date(c("2021-07-30", "2021-10-07", "2021-11-05", "2022-02-02"))
ticktext <- format(breaks, "%b %d")
tickvals <- as.numeric(breaks)

p <- ggplot(df, aes(fill = cond, text = name)) +
  geom_rect(aes(
    xmin = f_des, xmax = f_ces,
    ymin = as.numeric(uni) - .6 / 2, ymax = as.numeric(uni) + width / 2
  )) +
  scale_y_continuous(breaks = seq(levels(df$uni)), labels = levels(df$uni), expand = c(0.01, 0))

ggplotly(tooltip = c("text")) %>%
  layout(xaxis = list(
    ticktext = ticktext,
    tickvals = tickvals,
    tickcolor = "crimson", 
    gridcolor = "crimson"
  ))