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

ShinyApp中Plotly交互式图表无法正常显示的技术求助

ShinyApp中Plotly交互式图表无法显示的解决方法

以下是针对代码问题的修复方案,核心错误及修正点如下:

  • UI输出控件不匹配:Plotly交互式图表必须使用plotlyOutput,而非静态图表用的plotOutput
  • 函数拼写错误:修正plotly()→plot_ly()、as.charater→as.character、expresiom→expression
  • Reactive对象调用错误:channel_data <- channel_pipeline()已获取响应式数据,直接使用channel_data即可,无需加括号
  • Plotly对象未正确返回:用%>%连接plot_ly与layout,确保返回完整的交互式图表对象
  • 颜色参数错误:color_scale是已生成的颜色向量,直接传入colors = color_scale即可
  • CSS语法错误:闭合未完成的注释,避免样式失效

修正后的完整代码

library(shiny)
library(shinyWidgets)
library(shinyjs)
library(plotly)
library(ggplot2)
library(thematic)
library(ragg)
library(showtext)
library(dplyr)
library(lubridate)
library(RColorBrewer)

# 替换为你的文件路径
df <- read.csv("your_file_path.csv")
thematic_shiny(font = "Pacifico")

ui <- fluidPage(
  
  # Select theme
  shinythemes::themeSelector(),
  
  tags$style(HTML("
    body {
      font-family: 'Pacifico', 15; /*Set up fonts for the page */
    }
  ")),
  
  # Fix widgets
  tags$head(
    tags$script(HTML('
       $(document).ready(function() {
        // Get the position of the sidebar
        var sidebarPosition = $(".sidebar").offset().top;

        // Function to fix or unfix the sidebar based on scrolling
        function fixSidebar() {
          var scrollTop = $(window).scrollTop();

          if (scrollTop > sidebarPosition) {
            $(".sidebar").addClass("fixed-sidebar");
          } else {
            $(".sidebar").removeClass("fixed-sidebar");
          }
        }

        // Attach the function to the scroll event
        $(window).scroll(fixSidebar);

        // Call the function once to set the initial state
        fixSidebar();
      });
    '))
  ),
  
  # Application title
  titlePanel("Youtube Data science Channels Analytics"),
  
  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      sliderTextInput(
        inputId = "year_slider",
        label = "Select Year",
        choices = as.character(2017:2024),
        selected = "2023",
        width = "300px"
      )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel('View Count', plotlyOutput('view_plot')),
        tabPanel('Comment Count', plotlyOutput('comment_plot')),
        tabPanel('Like Count', plotlyOutput('like_plot'))
      )
    )
  )
)

server<-function(input, output) {
  
  df$channel <- as.factor(df$channel)
  
  #Filtering
  channel_pipeline <- reactive({
    
    df %>% 
      group_by(channel, Year) %>%
      summarize(
        viewCount = mean(viewCount), 
        commentCount = mean(commentCount), 
        likeCount = mean(likeCount)) %>% 
      arrange(Year, .by_group = T) %>% 
      filter(as.numeric(Year) %in% as.numeric(input$year_slider)) %>%
      as.data.frame()
  })
  
  # Define color scale
  color_scale <- brewer.pal(length(unique(df$channel)), "Spectral")
  
  # View Plot
  output$view_plot <- renderPlotly({
    channel_data <- channel_pipeline()
    
    plot_ly(data = channel_data, 
            x = ~as.character(channel), 
            y = ~viewCount*1e-3, 
            type = 'bar', 
            color = ~as.character(channel),
            colors = color_scale) %>%
      layout(xaxis = list(title = ''), 
             yaxis = list(title = expression(10^3)))
  })
  
  # Comments plot
  output$comment_plot <- renderPlotly({
    channel_data <- channel_pipeline()
    
    plot_ly(data = channel_data, 
            x = ~as.character(channel), 
            y = ~commentCount*1e-3, 
            type = 'bar', 
            color = ~as.character(channel),
            colors = color_scale) %>%
      layout(xaxis = list(title = ''), 
             yaxis = list(title = expression(10^3)))
  })
  
  # Likes plot
  output$like_plot <- renderPlotly({
    channel_data <- channel_pipeline()
    
    plot_ly(data = channel_data, 
            x = ~as.character(channel), 
            y = ~likeCount*1e-3, 
            type = 'bar', 
            color = ~as.character(channel),
            colors = color_scale) %>%
      layout(xaxis = list(title = ''), 
             yaxis = list(title = expression(10^3)))
  })
  
}

shinyApp(ui, server)

额外建议:将所有library调用放在代码开头,避免在server函数内重复加载包,提升代码可读性与执行效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:24:51