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

Shiny应用图表无法渲染:单独运行ggplot正常但应用内图表空白

问题根源及修复方案

你的Shiny应用图表空白的核心原因是UI输出控件与Server渲染函数不匹配,另外还有包加载的潜在问题,具体修复步骤如下:

1. 修正UI中的输出控件

你在Server中使用了renderPlotly()生成Plotly交互式图表,但UI里对应的是plotOutput()——这个控件仅支持静态ggplot或基础绘图输出,无法渲染Plotly对象。需要将UI中的plotOutput替换为plotlyOutput:

修改后的UI部分相关代码:

box(title = "Plot",
    solidHeader = TRUE,
    collapsible = TRUE,
    width = 12,
    plotlyOutput(outputId="myplot1")  # 替换原plotOutput
)

2. 确保加载所有必要的R包

你的代码中没有显式加载依赖包,虽然单独运行ggplot代码可能因为环境中已加载包而正常,但Shiny应用需要在代码开头明确加载所有用到的包:

library(shinydashboard)
library(ggplot2)
library(plotly)
library(scales)  # 用于date_breaks函数

3. 可选:检查日期格式匹配度

虽然你已经将COL1转为POSIXct,但如果CSV中的日期格式与"%m/%d/%Y %H:%M:%S"不完全匹配,可能导致日期解析异常。可以通过str(daily_data)确认COL1是否正确转为<POSIXct>类型,若有问题需调整format参数。

修复后的完整代码示例

# 加载依赖包
library(shinydashboard)
library(ggplot2)
library(plotly)
library(scales)

##----------DATA------------## 
path <- paste0("C:/WORK/TEMP") 
csv_path <- path 
daily_data <-   read.table(paste0(csv_path,"/file.csv"),
                           header = T,
                           sep = ',',
                           stringsAsFactors = F) 
daily_data$COL1 <-   as.POSIXct(daily_data$COL1, format = "%m/%d/%Y %H:%M:%S") 
str(daily_data)
##----------END DATA------------##

## UI 
ui <- dashboardPage(   
  dashboardHeader(title = "Test"),   
  dashboardSidebar(
    sidebarMenu(
      menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard"))
    )   
  ),   
  dashboardBody(
    tabItems(
      # First tab content
      tabItem(tabName = "dashboard",
              fluidRow(
                column(width = 5,
                       box(title = "Plot",
                           solidHeader = TRUE,
                           collapsible = TRUE,
                           width = 12,
                           plotlyOutput(outputId="myplot1")  # 修正为plotlyOutput
                       )
                )
              )
      )
    ) # end tabitems   
  ) # end dashboardbody 
) # end dashboardpage

## SERVER 
server <-   function( input, output ) {   
  output$myplot1 <- renderPlotly({
    ggplotly(
      ggplot(daily_data,
             aes(
               x = COL1,
               y = COL3,
               color = COL2
             )) +
        geom_line() +
        theme_bw() +
        scale_x_datetime(breaks = date_breaks("1 mins")) +
        labs(title = "My chart ", x = "Time", y = "%")
    )
  })
}

shinyApp( ui = ui, server = server )

内容的提问来源于stack exchange,提问作者J.S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:35:20