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

Shiny/R交互式图表无法显示且无报错问题求助

问题:Shiny R中交互式Plotly图表无法显示(无报错)

问题描述

使用Shiny制作包含介绍页和交互式图表页的CO₂排放报告,页面标题、侧边栏控件等功能正常,但交互式图表始终无法显示,RStudio控制台无任何报错信息。

错误分析及修复方案

你的代码存在两个核心问题导致图表无法渲染:

  1. 未正确调用反应式数据对象
    在server.R的renderPlotly函数中,你直接使用了反应式表达式内部的new_df变量,但反应式数据必须通过调用new_data()(带括号)来获取实时更新的数据集。

  2. UI代码存在语法隐患
    ui.R中p("intro text)缺少闭合双引号,虽不直接影响图表显示,但会触发语法警告;同时source("app_server.R")属于冗余代码,Shiny项目中UI与Server无需互相source,反而可能导致数据加载时机冲突。

修复后的完整代码

修复后的ui.R

library(shiny)

first_page <- tabPanel(
  "Introduction",
  titlePanel("CO2 Emissions around the World"),
  p("intro text")  # 修复缺失的闭合引号
)

second_page <- tabPanel(
  "Interactive Chart",
  titlePanel("CO2 Emissions Per capita of All Countries throughout History"),
  sidebarLayout(
    
    sidebarPanel(
      selectInput(
        inputId = "country_choice",
        label = "Choose a Country",
        choices = NULL  # 改为动态加载,避免UI初始化时数据未就绪
      ),
      
      sliderInput(
        inputId = "year_choice",
        label = "Year",
        min = 1950,
        max = 2021,
        value = c(1950, 2021),
        sep = ""
      ) 
    ),
    
    mainPanel(
      plotlyOutput("plot"),
      p("text caption")
    )
  )
)

ui <- navbarPage(
  "Climate change",
  first_page,
  second_page
)

修复后的server.R

library("shiny")
library("tidyverse")
library("ggplot2")
library("plotly")

climate_data <- read.csv("https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.csv")

server <- function(input, output, session) {
  
  # 动态更新国家选择框,确保数据加载完成后再渲染选项
  updateSelectInput(session, "country_choice", choices = unique(climate_data$country))
  
  new_data <- reactive ({
    climate_data %>%
      filter(country == input$country_choice) %>%
      filter(year >= input$year_choice[1]) %>%
      filter(year <= input$year_choice[2]) 
  })
  
  output$plot <- renderPlotly({
    # 正确调用反应式数据对象new_data()
    p <- ggplot(data = new_data(), aes(x = year, y = co2_per_capita)) + 
      geom_line()
    ggplotly(p)
  })
}

额外说明

  • 动态更新selectInput是为了避免UI初始化时,climate_data未完全读取导致的选择框加载失败问题;
  • 移除UI中的source语句,遵循Shiny项目的常规分离结构;
  • 核心修复点是在renderPlotly中调用new_data(),确保图表能获取实时过滤后的数据集。

内容的提问来源于stack exchange,提问作者Minty

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:15:25