0

I am building a shiny app and I would like to render a plot that is generated using the basic plot function in R into the mainPanel. The data used for the plot is simulated directly from a fitted model but I am not able to extract values into a data frame but all occur inside the plot() argument (i don't have to extract it as a data frame if I can find a solution on how to render my plot into the mainPanel).

I am a newbie into this, tried but no luck so far. How can I render the generated plot in the mainPanel of the app? below is an example code.

ui.r code:

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', ),#sidebarPanel

  mainPanel(
    fixedRow(
      imageOutput('PLOT', height = 600, width=1260) #?????
    )
     )#mainpanel
    )#sidebarLayout
 )#fluidPage
) #shinyUI

server.r code:

library(data.table)
library(flexsurv)
#load some data
data(pbc, package="randomForestSRC")
data <- as.data.table(na.omit(pbc))
data[,years := days/365.25]

shinyServer(function(input,output) {
  pred.data <- reactive({
    COVAL <- input$COVAL
    
    #fit the model
    fit <- flexsurvspline(Surv(years, status) ~ albumin, data=data, k=1, scale='hazard')
    
    #plot predictions using the fitted- at specific covariate value
    #COVAL=3
    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=c('green'))
    
    #plot <- recordPlot() #this one saves the plot as an object
    #plot.new() #
    
    #render the plot: ????
    output$PLOT <- renderImage(
      pred.data()
    )#
      
  })#reactive
})#shinyServer
Amer
  • 2,131
  • 3
  • 23
  • 38

1 Answers1

1
library(shiny)
library(data.table)
library(flexsurv)
#load some data
data(pbc, package="randomForestSRC")
data <- as.data.table(na.omit(pbc))
data[, years := days/365.25]


ui <- 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(
        plotOutput('PLOT', height = 600, width = 600) 
    )#mainpanel
  )#sidebarLayout
)#fluidPage


server <- function(input, output) {
  
  Fit <- reactive({
    #fit the model
    fit <- 
      flexsurvspline(Surv(years, status) ~ albumin, data=data, k=1, scale='hazard')
    
    return(fit)
  })#reactive
  
  output$PLOT <- renderPlot({
    ndata <- data.frame(albumin = input[["COVAL"]])
    fit <- Fit()
    plot(fit, est=FALSE, ci=FALSE, col.obs = 'black')
    lines(fit, newdata = ndata, ci=FALSE, col = 'green')
  })
  
}


shinyApp(ui, server)
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225