'Is there a way to set axis labels in r-plotly conditionally?

I would like to declutter a plot created with plotly and remove the repetitions of the year on the x-axis. The year should be shown only for the first month. For the rest of the labels the month (without the year) is enough. see image

I have tried to achieve this result with the ifelse function - without success (see reproducible example below). Is there any way to use ifelse or if_else to set the axis labels in plotly? I think it works that way in ggplot.

library(tidyverse)
library(plotly)

set.seed(42)

df <-
  data.frame(date = seq(ymd('2021-01-01'), ymd('2021-12-12'), by = 'weeks'),
             value = cumsum(sample(-10:20, length(seq(ymd('2021-01-01'), ymd('2021-12-12'), by = 'weeks')), replace = TRUE)))

df %>% 
  plot_ly(x = ~date, y = ~value) %>%
  add_lines() %>%
  layout(xaxis = list(dtick = "M1", tickformat = ~ifelse(date <= "2021-01-31", "%b\n%Y", "%b")))


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source