ggplot2 - How to plot multiple Y axis in data vizualization in R Plotly - Stack Overflow

I am trying to write a code which will plot multiple variables on a graph when the variables are clicke

I am trying to write a code which will plot multiple variables on a graph when the variables are clicked. The language is R and I am using Shiny to create an app. The following one is a sample.

library(shiny)
library(ggplot2)
library(plotly)
library(dplyr)
library(htmlwidgets)
library(ggthemes)
 
ui <- fluidPage(
  tags$head(
    tags$style(
      HTML("
        .app-title-container {
          position: -webkit-sticky;
          position: sticky;
          top: 0;
          z-index: 1001;
          background-color: #f8f9fa;
          padding: 10px;
          border-bottom: 2px solid #ddd;
        }
        
        .app-title {
          text-align: center;
          font-size: 28px;
          font-weight: bold;
          color: #1A5276;
          margin-top: 0;
          margin-bottom: 0;
        }
        
        .upbar {
          position: -webkit-sticky;
          position: sticky;
          top: 50px;
          z-index: 1000;
          background-color: #f8f9fa;
          padding: 10px;
          border-bottom: 2px solid #ddd;
          overflow: hidden;
        }
        
        .upbar.hidden {
          max-height: 0;
          padding: 0;
          border: none;
        }
        
        .checkbox-group-container {
          max-height: 150px;
          overflow-y: auto;
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          padding: 5px;
          margin: 10px;
        }
        
        .checkbox-group-container .checkbox-inline {
          width: 30%;
          white-space: nowrap;
          word-wrap: break-all;
          overflow-wrap: break-word;
          box-sizing: border-box;
          text-align: left;
          align-items: center;
          margin: 0px;
          justify-content: flex-start;
        }
 
        .plot-box {
          border: 2px solid #5DADE2; 
          padding: 10px; 
          margin-bottom: 20px;
          box-shadow: 0px 0px 5px 2px #A9CCE3;
        }
      ")
    )
  ),
  
  tags$script(
    HTML("
        $(document).ready(function() {
          $('#toggle-button').on('click', function() {
            $('.upbar').toggleClass('hidden');
            $(this).find('i').toggleClass('fa-chevron-up fa-chevron-down');
          });
        });
      ")
  ),
  
  div(class = "app-title-container",
      div(class = "app-title", "Dynamic Time Series Visualization")
  ),
  
  div(
    style = "text-align: right; padding-right: 10px;",
    actionButton("toggle-button", label = NULL, icon = icon("chevron-up"))
  ),
  
  div(class = "upbar",
      fluidRow(
        column(4, fileInput("file", "Choose CSV File", accept = c(".csv"))),
        column(4, numericInput("time", "Total Time (seconds)", value = 1000, min = 1)),
        column(4, downloadButton("download_pdf", "Download as PDF"))
      ),
      fluidRow(
        column(12, div(class = "checkbox-group-container", uiOutput("variable_selector")))
      )
  ),
  
  mainPanel(
    div(class = "plot-box", plotlyOutput("plot_output")),
    width = 12
  )
)
 
server <- function(input, output, session) {
  dataset <- reactive({
    req(input$file)
    df <- read.csv(input$file$datapath, check.names = FALSE)
    colnames(df) <- make.names(colnames(df), unique = TRUE)
    colnames(df) <- gsub("[. ]", "_", colnames(df))
    total_time <- input$time
    time_sequence <- seq(0, total_time, length.out = nrow(df))
    df$Time <- time_sequence
    return(df)
  })
  
  output$variable_selector <- renderUI({
    df <- dataset()
    checkboxGroupInput(
      inputId = "variables",
      label = "Select Variables to Plot",
      choiceNames = lapply(gsub("_", " ", names(df)[names(df) != "Time"]), function(name) {
        tags$div(class = "checkbox-inline", name)
      }),
      choiceValues = names(df)[names(df) != "Time"],
      inline = TRUE,
      width = "100%"
    )
  })
  
  output$plot_output <- renderPlotly({
    req(input$variables)
    df <- dataset()
    p <- plot_ly(data = df, x = ~Time)  # Initialize plotly object
    
    for (i in seq_along(input$variables)) {
      var <- input$variables[i]
      color <- scales::hue_pal()(length(input$variables))[i]
      
      # Add variable as a separate trace
      p <- add_lines(
        p,
        y = as.formula(paste0("~", var)),
        name = gsub("_", " ", var),
        line = list(color = color),
        yaxis = paste0("y", i)
      )
    }
    
    # Configure dynamic y-axes
    y_axes <- lapply(seq_along(input$variables), function(i) {
      list(
        title = gsub("_", " ", input$variables[i]),
        overlaying = if (i > 1) "y" else NULL,
        side = if (i %% 2 == 0) "right" else "left",
        showgrid = FALSE
      )
    })
    
    layout_args <- c(
      list(
        title = "Dynamic Time Series Visualization",
        xaxis = list(title = "Time (seconds)")
      ),
      setNames(y_axes, paste0("yaxis", seq_along(y_axes)))
    )
    
    p <- do.call(layout, c(list(p), layout_args))
    return(p)
  })
}
 
shinyApp(ui = ui, server = server)

What I am trying is that clicking each variable will create a new Y axis on either side (left or right) with its own scale, title, labels and their colour will be colour of the curve of that corresponding variable in the graph. So far I have managed to do this (In the first picture).

As you can see in the first picture, four variables are plotted, each with their own scale and labels but unfortunately they all get overlapped so the titles and scales and labels can't be read easily.

I want my graph will be like the 2nd photo

How should I do it? Can someone suggest me or edit my code? You can try this dataset to test Thank you in advance!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745604900a4635618.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信