qifengwu
qifengwu

Reputation: 129

How to print out the data frame along with ggplot2 charts in the same page in shiny

I am a little confused about printing the dynamic output while using R in shiny. The following are my code in shiny, it can just print out the ggplot2 charts, but not along with the new data frame. I just wanna know how to print out "mydata" at the same time. Thanks.

library("reshape2")
library("ggplot2")

Server.R

shinyServer(function(input, output) {

output$main_plot <- renderPlot({
    #Draw gragh to compare the forecast values with real data
    mydata <- data.frame(years, A, B)   
    df <- melt(mydata,  id = 'years', variable = 'series')      
    print(ggplot(df, aes(years,value)) + geom_line(aes(colour = series), size=1.5))
    
})

Ui.R

shinyUI(pageWithSidebar(

# Sidebar with controls to select a dataset
# of observations to view
 
sidebarPanel(
 
selectInput("dataset", "Choose a dataset:", 
      choices = c("Netflix"))),
  
plotOutput(outputId = "main_plot", height = "500px")
 
))

Upvotes: 1

Views: 1952

Answers (1)

Joe Cheng
Joe Cheng

Reputation: 8061

Pull out the data frame into a reactive expression, so you can use it from two different outputs. (This is the reactive analog to introducing and reusing a variable.)

server.R

shinyServer(function(input, output) {

    mydata <- reactive({
        data.frame(years, A, B)
    })

    output$main_plot <- renderPlot({
        #Draw gragh to compare the forecast values with real data
        df <- melt(mydata(),  id = 'years', variable = 'series')      
        print(ggplot(df, aes(years,value)) + geom_line(aes(colour = series), size=1.5))

    })

    output$data <- renderTable({ mydata() })
})

ui.R

shinyUI(pageWithSidebar(

# Sidebar with controls to select a dataset
# of observations to view

sidebarPanel(

selectInput("dataset", "Choose a dataset:", 
      choices = c("Netflix"))),

plotOutput(outputId = "main_plot", height = "500px"),
tableOutput(outputId = "data")

))

Upvotes: 1

Related Questions