'How can I add a subcategory to axis in Plotly with R?

I am trying to add a second category to x axis with Plotly under R like this:

enter image description here

Here is my code:

library(plotly)

data <- data.frame(day=  c(1:4),
                   visit = c("visit1","visit1", "visit2", "visit2"),
                   val = c(1:4),
                   flag = c("","","", 1))

fig <- plot_ly(data= data, x = ~day) %>%
  
  add_trace(y = ~val,
            type = 'scatter',
            mode = 'lines+markers',
            line = list(width = 2, 
                        dash = 'solid')) %>%
  
  add_trace(data= data %>% filter(flag == 1), y = 0, 
            type = 'scatter', 
            hoverinfo = "text",
            mode = 'markers',
            name = "flag",
            text = paste("<br>N°",data$ID[data$flag == 1], 
                         "<br>Day",data$day[data$flag == 1]),
            marker = list(
              color = 'red',
              symbol = "x",
              size = 12
            ),
            showlegend = T
  )

fig

Without Category

I have tried this, which seems good but the markers disappear from the graph, maybe due to the filter on data.

library(plotly)

data <- data.frame(day=  c(1:4),
                   visit = c("visit1","visit1", "visit2", "visit2"),
                   val = c(1:4),
                   flag = c("","","", 1))

fig <- plot_ly(data= data, x = ~list(visit,day)) %>%
  
  add_trace(y = ~val,
            type = 'scatter',
            mode = 'lines+markers',
            line = list(width = 2, 
                        dash = 'solid')) %>%
  
  add_trace(data= data %>% filter(flag == 1), y = 0, 
            type = 'scatter', 
            hoverinfo = "text",
            mode = 'markers',
            name = "flag",
            text = paste("<br>N°",data$ID[data$flag == 1], 
                         "<br>Day",data$day[data$flag == 1]),
            marker = list(
              color = 'red',
              symbol = "x",
              size = 12
            ),
            showlegend = T
  )

fig

Category without filter



Sources

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

Source: Stack Overflow

Solution Source