Home > database >  how to resolve the expression in the ggplot r shiny
how to resolve the expression in the ggplot r shiny

Time:12-31

aI am trying to pass a expression into the ggplot of r shiny app and generate the graph, however it seems not working . Any suggestion is appreciated

in the code below, i am trying to render a plot where i am using the input$xaxis and input$yaxis, while i pass the input$xaxis which is a character needs to be considered as a variable in aes(), so instead of using the aes() i am using the aes_string(). Now, i am trying to pass an expression so that i can reorder the input$xaxis with a variable. but its not working.


library(shiny)
library(tidyverse)
library(tidyCDISC)
library(DT)
library(shinyjs)
library(timevis)
library(rlang)

data('advs', package = 'tidyCDISC')
advs <- advs %>% rename_all(tolower) %>% filter(anl01fl=='Y')

parvs <- unique(advs$param)
usubjid <- unique(advs$usubjid)

ui <- fluidPage(
  
  titlePanel("Patient Profile"),
  
  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      selectInput("subj",
                  "Please Select a USUBJID",
                  choices = usubjid,
                  selected = usubjid[1])
    ),
    
    # Show a plot of the generated distribution
    mainPanel(tags$div(selectInput('para', 'Parameter', choices = parvs), style="display:inline-block"),
         tags$div(selectInput('yaxis', 'Analysis Y Variable', choices = list('aval','chg', 'pchg')), style="display:inline-block") ,
                 tags$div(selectInput('xaxis', 'Analysis X Variable', choices = list('ady','visit', 'avisit')), style="display:inline-block") ,
                 plotOutput("plot2"))
      )
    )


server <- function(input, output, session) {
  output$plot2 <- renderPlot({
    req(input$para, input$yaxis)
    if (input$xaxis=='ady') {
      xaxis <- expr('ady')
    } else if (input$xaxis=='visit') {
      xaxis <- parse_expr("reorder(input$xaxis, 'visitnum')")
    } else if (input$xaxis=='avisit') {
      xaxis <- expr(reorder(input$xaxis, 'avisitn'))
    }
    ggplot(advs %>% filter(usubjid==input$subj & param==input$para), aes_string(x=eval_tidy(xaxis),y=input$yaxis, group='atpt'))   
      geom_line(aes(color=atpt))  
      ggtitle(paste(input$para, 'Line Plot'))
  })
}

shinyApp(ui, server)

CodePudding user response:

Instead of aes_string() which is deprecated you can use aes() with .data pronoun:

  output$plot2 <- renderPlot({
    req(input$para, input$yaxis)
    if ( input$xaxis == 'ady') {
      xaxis <- 'ady'
    } else if ( input$xaxis == 'visit') {
      xaxis <- 'visitnum'
    } else if ( input$xaxis == 'avisit') {
      xaxis <- 'avisitn'
    }
    advs %>% 
      filter(usubjid == input$subj & param == input$para) %>%
      ggplot( aes( x = .data[[xaxis]], y = .data[[input$yaxis]], group = 'atpt'))   
      geom_line( aes( color = atpt ))  
      ggtitle(paste(input$para, 'Line Plot'))
  })
  • Related