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

如何在Shiny应用中通过ggplotly()显示文本?

能否在Shiny应用中用ggplotly()显示文本?

可以实现,但你提供的代码写法有误——ggplotly()只能接收ggplot图形对象作为输入,而非直接传入renderText()的输出。下面是正确的实现方式:

核心思路

先通过ggplot创建包含文本的基础图形(比如用annotate()或geom_text()添加文本内容),再将这个ggplot对象传入ggplotly()转换为交互式plotly对象,最后在Shiny的server端用renderPlotly()返回该对象,对应ui端的plotlyOutput()。

修正后的完整代码

library(plotly)
library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel("HTML"),
  sidebarLayout(
    sidebarPanel(),
    mainPanel(
      textOutput("testHTML"),
      plotlyOutput("PLOTLYTEXT")
    )
  )
))

server <- shinyServer(function(input, output) {
  output$testHTML <- renderText({
    "text"
  })
  
  output$PLOTLYTEXT <- renderPlotly({
    # 创建带文本的ggplot对象
    p <- ggplot() +
      annotate("text", x = 1, y = 1, label = "这是用ggplotly显示的文本", size = 5) +
      # 隐藏坐标轴和背景,仅保留文本
      theme_void()
    
    # 将ggplot对象转为plotly交互式对象
    ggplotly(p)
  })
})

shinyApp(ui = ui, server = server)

关键说明

  • 若需要动态文本(比如根据用户输入变化),可将文本内容替换为响应式变量(如input$xxx或reactive返回的值)
  • theme_void()用于隐藏默认坐标轴和网格,若需保留图形框架可移除该行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:20:23