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

Shiny应用中图表选择可视化异常问题求助

问题分析

你的代码里,renderPlot(num())传递的是字符串(比如"Chart1"),但renderPlot()需要接收的是生成可视化对象的表达式,而不是字符串,所以无法渲染出图表。

解决方法

可以通过switch()函数根据下拉选择的字符串,返回对应的预先生成的图表对象;或者将图表存入列表,通过名称索引调用。下面是修正后的完整代码:

---
title: "Test App"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
# Libraries ----
# App
library(flexdashboard)
library(shiny)
library(shinyjs)
library(shinyWidgets)

# Core
library(tidyverse)
library(tidyquant)

# Visualizations
library(ggplot2)

# Data
data <- mtcars
data$cyl <- as.factor(data$cyl)

Column {.sidebar}

useShinyjs(rmd = TRUE)

selectInput("clusterNum", label = h4("Charts"), 
     choices = list("Chart1" = "Chart1", "Chart2" = "Chart2"), 
     selected = "Chart1")

Column {data-width=650}

Chart

# 预定义图表
Chart1 <- qplot(x = data$wt, y = data$mpg)
Chart2 <- qplot(data$cyl, geom = "bar")

renderPlot({
  # 根据输入选择对应的图表
  switch(input$clusterNum,
         "Chart1" = Chart1,
         "Chart2" = Chart2)
})
# 修改说明
- 移除了多余的`num <- reactive(input$clusterNum)`,直接在`renderPlot()`里使用`input$clusterNum`
- 在`renderPlot()`的表达式中,用`switch()`函数匹配输入的字符串,返回对应的ggplot图表对象,这样Shiny就能正确渲染可视化内容。

内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:35:45