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

R Shiny应用中ggplot2绘图超时且无法显示问题求助

Fixing Your R Shiny App: Timeout & Plot Display Issues

Let's break down why your app is failing to render plots and fix each issue step by step:

Key Problems in Your Original Code

  1. Undefined Variables: You used mymean, mysd, mylmean, mylsd and distname without ever assigning values to them—this causes critical errors in the plotting logic.
  2. Incorrect Lognormal Parameter Calculation: Converting input mean/sd to lognormal parameters (meanlog/sdlog) by simply taking the log is mathematically wrong. Lognormal distribution parameters require specific transformations based on its mean/variance formulas.
  3. Unnecessary Data Generation: You generated both normal and lognormal data regardless of user selection, wasting resources.
  4. Redundant plot(p) Call: grid.arrange returns a plot object directly—calling plot(p) again is unnecessary and can cause rendering issues.

Corrected Full Code

library(shiny)
library(ggplot2)
library(gridExtra)
set.seed(15)

ui <- fluidPage(
  titlePanel("正态分布与对数正态分布拟合对比"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("mean", "均值:", min = 1, max = 250, value = 10),
      sliderInput("spread", "标准差:", min = 0.1, max = 25, step=0.1, value = 2.5),
      sliderInput("n", "数据点数量:", min = 10, max = 10000, value = 2500),
      selectInput("dist", "选择数据分布:",
                  list("正态分布"="dnorm", "对数正态分布"="dlnorm")),
      # Add note for lognormal constraint
      helpText("提示:对数正态分布的标准差必须小于均值")
    ),
    mainPanel(
      plotOutput("distPlot", height = "80vh")
    )
  )
)

server <- function(input, output) {
  sim_data <- reactive({
    req(input$dist, input$spread, input$mean)
    
    if (input$dist == "dnorm") {
      # Generate normal data with input params
      dat <- data.frame(value = rnorm(input$n, mean = input$mean, sd = input$spread))
    } else {
      # Validate lognormal parameter constraint
      if (input$spread >= input$mean) {
        return(data.frame(value = numeric(0)))
      }
      # Calculate correct lognormal parameters from input mean/sd
      mu <- input$mean
      sigma <- input$spread
      
      s_squared <- -log(1 - (sigma^2)/(mu^2))
      s <- sqrt(s_squared)
      m <- log(mu) - s_squared/2
      
      dat <- data.frame(value = rlnorm(input$n, meanlog = m, sdlog = s))
    }
    return(dat)
  })

  output$distPlot <- renderPlot({
    dat <- sim_data()
    req(dat)
    
    # Handle invalid lognormal parameter case
    if (nrow(dat) == 0) {
      return(ggplot() +
               annotate("text", x = 0, y = 0, label = "错误:对数正态分布的标准差必须小于均值!", size = 5, color = "red") +
               theme_void())
    }
    
    # Calculate theoretical parameters for density functions
    norm_mean <- input$mean
    norm_sd <- input$spread
    
    # Compute lognormal parameters from input (valid only if spread < mean)
    ln_s_squared <- -log(1 - (input$spread^2)/(input$mean^2))
    ln_s <- sqrt(ln_s_squared)
    ln_m <- log(input$mean) - ln_s_squared/2
    
    # Build histogram plot
    hist_plot <- ggplot(dat, aes(x = value)) +
      geom_histogram(aes(y = ..density..), colour = "black", fill = "white", bins = 30) +
      stat_function(fun = dnorm, colour ="#377EB8", args = list(mean = norm_mean, sd = norm_sd)) +
      stat_function(fun = dlnorm, colour ="#E41A1C", args = list(meanlog = ln_m, sdlog = ln_s)) +
      geom_density(colour="black") +
      labs(y = "密度", x = "数值") +
      theme_minimal()
    
    # Add title based on selected distribution
    if (input$dist == "dnorm") {
      hist_plot <- hist_plot + labs(title = "正态分布数据拟合")
    } else {
      hist_plot <- hist_plot + labs(title = "对数正态分布数据拟合")
    }
    
    # Build box plot
    box_plot <- ggplot(dat, aes(x = "", y = value)) +
      geom_boxplot() +
      labs(title = "数据箱线图", y = "数值") +
      theme_minimal() +
      theme(axis.title.x = element_blank(), axis.text.x = element_blank())
    
    # Arrange plots
    grid.arrange(hist_plot, box_plot, ncol = 1, nrow = 2, heights = c(4, 2))
  })
}

shinyApp(ui = ui, server = server)

What Changed & Why

  1. Valid Lognormal Parameter Calculation: We use the correct mathematical transformations to convert input mean/sd to meanlog/sdlog for lognormal data, ensuring the generated data matches the user's desired mean and spread.
  2. Error Handling: Added validation for lognormal parameters (std dev must be less than mean) and a clear error message when this constraint is violated.
  3. Cleaner Data Generation: Only generate data for the selected distribution, reducing unnecessary computation.
  4. Defined All Variables: All parameters used in stat_function are explicitly calculated from user inputs.
  5. Improved Plot Layout: Removed redundant plot(p) call and adjusted theme elements for better readability.

This should resolve the timeout and plot display issues while making your app more robust and user-friendly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:28:45