Проблема с реактивной полосой в приложении Shiny

#r #plot #shiny #shinyapps #shiny-reactivity

Вопрос:

Я пытаюсь создать блестящее приложение, которое реактивно создает эту гистограмму. Это гистограмма, которая показывает количество вакцинированных людей по вертикальной оси и область, такую как Нью-Йорк или Бостон, по горизонтальной оси.

Я включаю полный код, я не знаю, почему, если я вставлю hchart: y = df [, 2], это сработает, но если я вставлю y = df [, colm], это не сработает. Есть какие-нибудь предложения?

 
# Libraries
libraries <- c("jsonlite", "ggplot2")

for(lib in libraries){
  eval(bquote(library(.(lib))))
}

if (!require("pacman")) install.packages("pacman")
pacman::p_load(shiny, ggplot2, plotly, shinythemes, shinyWidgets, highcharter, DT)

df = data.frame(
  zone = c("Boston", "NY", "Chicago"),
  teenagers = c(533, 489, 584),
  adults = c(120, 201, 186),
  elder = c(156, 153, 246)
)


ui2 <- navbarPage(
  
  paste('Vaccination Evolution in USA'),
  
  theme = shinytheme("cerulean"),
  
  tabPanel('Evolution by age',
           
           sidebarLayout(
             
             sidebarPanel(
               selectInput('variable', h5('Select the age range to visualize'),
                           choices = c("Teens" = 2,
                                       "Adults" = 3, 
                                       "Elder" = 4), 
                           selected=2
                          ),
               helpText("Age range in USA")
                         ),
             
             mainPanel(
               textOutput("text1"),
               titlePanel(h4('Evolution of the vaccination in USA by age and zone')),
               highchartOutput('histogram'),
               br(),
               helpText("Interact with the graph")
                      )
             
                     )
          )
     )





#   Server building
server2 <- function(input, output) {
  
  output$text1 <- renderText({ 
    colm = as.numeric(input$variable)
    paste("Age group shown is:", names(df[colm]))
    
  })
  
  output$histogram <- renderHighchart({
    
    colm = as.numeric(input$variable)
    
    hchart(df, type = 'column', hcaes(x = df[, 1], y = df[, colm]), name = "Number of people vaccinated")%>%
      
      hc_title(text = paste("Number of people vaccinated with at least one dose" ),
               style = list(fontWeight = "bold", fontSize = "20px"), align = "center")%>% 
      
      hc_yAxis(title=list(text=paste("Number")))%>%
      
      hc_xAxis(title=list(text=paste('Region')))%>%
      
      hc_add_theme(hc_theme_ggplot2())
  })
  
  
}

#shiny APP
shinyApp(ui = ui2, server = server2)

 

Ответ №1:

Вы должны передавать имена переменных в hcaes . Переменная y есть names(df[colm])) , и ее можно преобразовать в символьное выражение с помощью !!sym() :

 output$histogram <- renderHighchart({
        
        colm = as.numeric(input$variable)
        
        hchart(df, type = 'column', hcaes(x = zone, y = !!sym(names(df[colm]))), name = "Number of people vaccinated")%>%
            
            hc_title(text = paste("Number of people vaccinated with at least one dose" ),
                     style = list(fontWeight = "bold", fontSize = "20px"), align = "center")%>% 
            
            hc_yAxis(title=list(text=paste("Number")))%>%
            
            hc_xAxis(title=list(text=paste('Region')))%>%
            
            hc_add_theme(hc_theme_ggplot2())
    })
 

Комментарии:

1. Братан, ты мой герой!

2. Не забудьте пометить вопрос как решенный, если он решил вашу проблему