Shiny中如何将reactive拟合模型生成的plot渲染到mainPanel
解决方案
你之前的写法存在两个核心问题:
- UI端不需要用
imageOutput,渲染R基础绘图直接用plotOutput即可 - Server端不需要把绘图逻辑套在
reactive里,也不用调用renderImage,直接用renderPlot包裹所有绘图代码就行,Shiny会自动处理基础plot的渲染
修改后完整代码
ui.R
library(shiny) shinyUI(fluidPage( fluidRow( column(12,h1('TITLE'), align='middle') ), hr(), sidebarLayout( sidebarPanel( sliderInput('COVAL', 'Covariate value', min=1, max=5, value=3,step=1), align='left' ), mainPanel( fixedRow( plotOutput('PLOT', height = 600, width=1260) ) ) ) ))
server.R
library(data.table) library(flexsurv) # 加载数据 data(pbc, package="randomForestSRC") data <- as.data.table(na.omit(pbc)) data[,years := days/365.25] shinyServer(function(input,output) { output$PLOT <- renderPlot({ COVAL <- input$COVAL # 拟合模型 fit <- flexsurvspline(Surv(years, status) ~ albumin, data=data, k=1, scale='hazard') # 所有绘图逻辑直接写在这里即可,无需额外提取数据框 ndata = data.frame(albumin=COVAL) par(mfrow=c(1,1)) plot(fit, est=F, ci=F, col.obs = 'white') lines(fit, newdata = ndata, ci=F, col='green') }) })
补充说明
你不需要额外把绘图数据提取为数据框,所有plot()、lines()相关的绘图逻辑直接放在renderPlot的花括号里就可以正常渲染,renderPlot会自动捕获所有R基础绘图函数生成的图像,输出到对应的plotOutput组件。
如果后续要调整图像参数,比如分辨率、边距之类的,可以直接在renderPlot里加res、pointsize等参数,或者在绘图代码里调整par的设置即可。
内容的提问来源于stack exchange,提问作者Amer
相关产品推荐
相关产品推荐

