Duplicated x axis label when applying Plotly in Shiny app

The chart reponds super odd when select more than one states input. The x axis does not show up right or show duplicated dates. The graph is not working. I tried to use a loop to over StateFull name for adding a trace in the graph and was not able to get it fixed.

library(usmap) 
library(shiny)
library(ggplot2) #use ggplot2 to add layer for visualization
library(maps)
library(openxlsx)
library(readxl)
library(dplyr)
library(tidyr)

library(tidytuesdayR) # to get tidytuesday data
library(tidyverse) # for ggplot
library(janitor) # for clean_names
library(ggeasy) # making ggplot customisation easy
library(gganimate) # for animating map by year
library(transformr) # i think i need this for gganimate
library(patchwork) # to patch plots together
library(PNWColors)

library(tidyquant)
library(plotly)
library(DT)
library(ggrepel)
library(tidyr)
library(shinycssloaders)
library(shinythemes)

library(shinyBS)
library(scales)
library(shinyWidgets)
library(bslib)

set.seed(123)  # Ensure reproducibility

sample_data <- data.frame(
  Date = as.Date(c("2024-08-13", "2024-08-13", "2024-08-13", "2024-08-13", 
                   "2024-08-13", "2024-08-13", "2024-08-13", "2024-08-13",
                   "2024-08-14", "2024-08-14", "2024-08-14", "2024-08-14",
                   "2024-08-14", "2024-08-14", "2024-08-14", "2024-08-14",
                   "2024-08-15", "2024-08-15", "2024-08-15", "2024-08-15",
                   "2024-08-15", "2024-08-15", "2024-08-15", "2024-08-15")),
  Type = rep(c("A","B"), 12),
  state = rep(c("AZ", "CA", "CT"), each = 8),
  value = rep(0, 24),
  fruit = rep(c("Orange", "Apple"), 12),
  StateFull = rep(c("Arizona", "California", "Connecticut"), each = 8),
  Percent_byStateFruit = sample(c(1, 0, 0.98), 24, replace = TRUE) 
)


print(sample_data)


head(sample_data)

ui <- fluidPage(
  tabPanel("Time Series", fluid = TRUE, icon = icon("chart-bar"),
           titlePanel("Time Series"),
           fluidRow(
             column(6,
                    pickerInput(inputId = "TimeSeriesSelectState",
                                label = "Select States",
                                choices = c("Arizona", "California", "Connecticut"),  # Make sure averaged_data$Type is available
                                multiple = TRUE,
                                options = list(`actions-box` = TRUE,
                                               title='Enter state name')
                    ),
                    selectizeInput(inputId = "TimeseriesFruit",
                                   label = "Select  (Max 2)",
                                   choices = c("Orange","Apple"),  # Make sure averaged_data$Type is available
                                   multiple = TRUE,
                                   options = list(maxItems = 2, placeholder = 'select  name',
                                                  onInitialize = I('function() { this.setValue(""); }'))
                    ),
         
                    
             ),
             column(6,
                    dateRangeInput("date", "Date:",   
                                   start = "2024-08-13",
                                   end   = Sys.Date()+2),
            
                    
                    radioButtons("fruit", "Choice of Fruit", 
                                 choices = c("Orange", "Apple"), 
                                 selected = "Orange"),
                    helpText("Note: adding notes")
             )
           ),
           hr(),
           fluidRow(
             column(8,offset=2,
                    plotlyOutput("plot1")
             )
           )
  )  
) 


#titlePanel("US Election Tracker"),
#server started
server <- function(input, output) {
#--------Time Series Tab Line Chart
Count_data <- reactive({
  req(input$TimeseriesFruit) 
  req(input$TimeSeriesSelectState)
  req(input$date)
  req(input$fruit)
  filter(sample_data, Type %in% input$TimeseriesFruit) %>%
    filter(StateFull %in% input$TimeSeriesSelectState) %>%
    filter(Date %in% input$date)%>%
    filter(fruit %in% input$fruit) 
  
})

output$plot1 <- renderPlotly({
input$EnterTimes
input$TimeseriesFruit
input$TimeSeriesSelectState
input$date
input$fruit
isolate({
    # Initialize the plotly object
    fig <- plot_ly(Count_data())
    # Loop through each selected state and add a trace for it
    for (k in seq_along(input$TimeSeriesSelectState)) {
      state_data <- Count_data()[Count_data()$StateFull == input$TimeSeriesSelectState[k], ]
      fig <- add_trace(fig, data = state_data, 
                       x = ~Date, y = ~Percent_byStateFruit, type = 'scatter', mode = 'marker',
                       name = input$TimeSeriesSelectState[k],
                       line = list(width = 2)) %>%
        layout(
          title = "Trend",
          xaxis = list(title = "Date",
                       tickformat = "%b %d, %Y"),
          yaxis = list(
            title = "Percent",
            tickformat = ".2%",  
            range = c(-0.5, 1.5),
            tickmode = "linear",
            dtick = 0.2
          )
        )
    }
    fig  # Return the plotly figure

})
})
}


shinyApp(ui = ui, server = server)

Unintended Result:

I expect a good looking and working time series line chart.

New contributor

Snow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật