You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny应用选择国家子集与坐标轴变量后散点图无法显示问题排查

问题定位与修复方案

你的Shiny应用散点图无法显示是由以下几个明确的代码错误导致的:

  • 下拉选择框初始默认值不合法:Y轴选择框的可选值只有total_deaths、new_deaths,但你设置的初始选中值是不存在的Deaths;X轴选择框的初始选中值Comparator variables也不在数据集列名范围内,导致初始绘图时找不到对应变量
  • plotly参数传入错误:input$x和input$y是字符串类型的变量名,plotly默认不会把字符串解析为数据集的列,需要显式声明要取数据集对应的列
  • 国家选择框存在重复选项:直接用covid$location作为选项会把每行的国家都列出来,应该去重
  • 下载功能的格式匹配错误:UI里单选框的文本是Text(tsv),但server的switch判断用的是Text (tsv)(多了空格),会导致匹配失败
  • Output类型不匹配:output$location用的是renderPrint,但UI里对应组件是textOutput,类型不兼容
修正后的完整代码
library(shiny)
library(plotly)
library(DT)
covid <- read.csv("D:/R/EuropeIndia.csv")
title <- tags$a(href='https://ourworldindata.org/covid-vaccinations?country=OWID_WRL',
                'COVID 19 Vaccinations')

# Define UI for application that draws a histogram
ui <- fluidPage(
  headerPanel(title = title),

  # Application title
  titlePanel("COVID vaccinations: Deaths Vs All variables"),

  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      selectInput("location", "1. Select a country",
                  choices = unique(covid$location), selectize = TRUE, multiple = FALSE),
      br(),
      helpText("Select variables to plot"),
      selectInput(inputId = "y", label = "Y-axis:",
                  choices = c("total_deaths", "new_deaths"),
                  selected = "total_deaths"),
      br(),
      selectInput(inputId = "x", label = "X- axis:",
                  choices = names(covid),
                  selectize = TRUE,
                  selected = names(covid)[1]),
      
      br(),
      helpText("Select the Download Format"),
      radioButtons("type", "2. Format type:",
                   choices = c("Excel (csv)", "Text (tsv)", "Doc")),
      br(),
      helpText("Click on the download button to download dataset"),
      downloadButton("downloadData", "Download"),
      helpText("READ ME: Click on the title to open data source")
      
    ),

    # Show a plot of the generated distribution
    mainPanel(
      verbatimTextOutput("location"),
      plotlyOutput("scatterplot"),
      tabsetPanel(
        type = "tabs",
        tabPanel("Summary of COVID data", verbatimTextOutput("summary")),
        tabPanel("Dataset", DTOutput("dataset"))
      )
      
    )
  )
)

# Define server logic 
server <- function(input, output) {
  # 抽离过滤后的数据集为公共响应式变量,避免重复计算
  filtered_data <- reactive({
    subset(covid, location == input$location)
  })
  
  output$location <- renderPrint({
    filtered_data()
  })
  
  output$scatterplot <- renderPlotly({
    req(input$x, input$y) # 确保变量存在时再绘图
    plot_ly(filtered_data(), 
            y = ~.data[[input$y]],
            x = ~.data[[input$x]],
            type = 'scatter', 
            mode = "markers")
  })
  output$summary <- renderPrint({
    summary(covid)
  })
  datasetinput <- reactive({covid})
  fileExt <- reactive({
    switch(input$type,
           "Excel (csv)" = "csv", "Text (tsv)" = "tsv", "Doc" = "doc")
  })
  output$dataset <- renderDT(
    covid, options = list(
      pageLength = 50,
      initComplete = JS('function(setting, json) { alert("done"); }')
    )
  )
  
  output$downloadData <- downloadHandler(
    filename = function(){
      paste("covid", fileExt(),sep = ".")
    },
    content = function(file){
      sep <- switch(input$type,
                    "Excel (csv)" = ",", "Text (tsv)" = "\t", "Doc" = " ")
      write.table(datasetinput(), file, sep = sep, row.names = FALSE)
    }
    
  )
}

# Run the application 
shinyApp(ui = ui, server = server)
额外优化说明

把过滤后的国家数据集抽成了公共响应式变量filtered_data,避免多个地方重复写subset逻辑,后续修改过滤条件只需要改一处即可。

内容的提问来源于stack exchange,提问作者Hari Chandana Bollimpalli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:06:10