You need to enable JavaScript to run this app. 如何在R Markdown中通过selectInput与actionButton输出对应本地图片
优惠活动
大模型
产品
解决方案
定价
更多

如何在R Markdown中通过selectInput与actionButton输出对应本地图片

存在的问题

  • 下拉框初始选中值不合法:你给selectizeInput设置的可选choices只有Slc2a1,但初始选中selected设为了Sele,不在可选列表范围内,初始触发时会拼接出不存在的图片路径。
  • 图片渲染逻辑错误:knitr::include_graphics是静态Rmd渲染阶段插入图片的函数,不能用在shiny的响应式逻辑里;且renderPlot仅支持渲染R生成的绘图对象,不支持直接渲染本地静态图片。

修复方案

把动态渲染图片的逻辑换成shiny原生的renderUI + tags$img组合,同时修正下拉框的初始值配置,完整可运行的修复后代码如下:

---
title: "123"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    social: menu
    source_code: embed
runtime: shiny
editor_options: 
  chunk_output_type: inline
---

```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
abc {.sidebar }

Search with mouse gene symbol, the results will be displayed beside:

inputPanel(
      selectizeInput(
        "selectGeneSymbol", 
        "what selected:", 
        choices = c("Slc2a1"), # 后续新增可选基因直接往该向量里加即可
        multiple = F,
        width = 360,
        selected = "Slc2a1" # 初始值必须在choices列表范围内
      )
)

actionButton(inputId = "plot1", label = "plot1")
Home {.tabset}
# 输出图片的UI占位
uiOutput("gene_image")

# 点击按钮后响应式渲染图片
output$gene_image <- renderUI({
  req(input$plot1) # 仅在按钮点击后才执行渲染逻辑
  img_path <- paste0(input$selectGeneSymbol,"_FPKM.png")
  # 图片不存在时给出友好提示,避免直接报错
  validate(need(file.exists(img_path), "对应基因的图片不存在,请检查文件名和存储路径"))
  tags$img(src = img_path, width = "100%")
})
## 注意事项
- 所有基因对应的图片都需要放在和该Rmd文件同级的目录下
- 图片命名必须严格遵循`[基因名]_FPKM.png`的格式,基因名大小写和`selectizeInput`的`choices`配置完全一致

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

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

最近更新时间:2026.10.18 21:24:03