最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin6PV0评论

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!

Post a comment

comment list (0)

  1. No comments so far