JeniFav
JeniFav

Reputation: 117

Shiny - plots don't render - no error code

Here's my code:

download.file("http://pub.data.gov.bc.ca/datasets/176284/BC_Liquor_Store_Product_Price_List.csv", "bcl_prices.csv")



ui <- shinyUI(fluidPage(

navbarPage("Analysis Application",


# First panel - upload data and give summary

tabPanel("Upload Data",
       sidebarLayout(
            sidebarPanel(
                #Selector for file upload
                fileInput('datafile', 'Choose data file',
                accept='.csv', width='100%')
        ),

        mainPanel(                  
            verbatimTextOutput("desc"),
            br(),
            verbatimTextOutput("sum")
        )
    ) 
),

# Second panel - graph data

tabPanel("Plot Data",
    sidebarLayout(
          sidebarPanel(
            uiOutput("graphtype"),
            uiOutput("dependent"),
            uiOutput("independent")                 
          ),
          mainPanel(
                plotOutput('plot')
          )
    )
)
)
))






server <- shinyServer(function(input, output) {


# First panel - load data and see summary
#This function is repsonsible for loading in the selected file
filedata <- reactive({
        infile <- input$datafile
        if (is.null(infile)) {
    # User has not uploaded a file yet
    return(NULL)
        }
        read.csv(infile$datapath, stringsAsFactors = T)
})  

#This previews the CSV data file
output$desc <- renderPrint({
    str(filedata())
})
    output$sum <- renderPrint({
        dat <- filedata()
        summary(dat)    
    })

# Second panel - choose variables for plotting

# Choose graph type 
output$graphtype <- renderUI({
    grphtp <- c("Histogram", "Boxplot", "Bar chart", "Line chart",  "Scatterplot")
    selectInput("graphtype", "Graph Type", grphtp)
})

# Choose dependent variable, based on graph type
output$dependent <- renderUI({
    if(is.null(input$graphtype) || is.na(input$graphtype)) {
        return()
    }
    dat <- filedata()[,sapply(filedata(), is.numeric)]
    colnames <- names(dat)
    colnames
    if(input$graphtype == "Histogram"){
    selectInput("dependent", "Variable",  colnames)
    } else {
    selectInput("dependent", "Dependent Variable",  colnames)
    }
})

# Choose independent variable, based on graph type
output$independent <- renderUI({
    if(is.null(input$graphtype) || is.na(input$graphtype)) {
        return()
    }
    if(input$graphtype == "Histogram"){
    return(NULL)
    } else if(input$graphtype == "Bar chart" | input$graphtype == "Box plot") {
    dat2 <- filedata()[,sapply(filedata(), is.factor) | sapply(filedata(), is.character)]
    colnames2 <- names(dat2)
    colnames2
    selectInput("independent", "Independent Variable",  colnames2)
    } else {
    dat3 <- filedata()[,sapply(filedata(), is.numeric) | sapply(filedata(), is.integer)]
    colnames3 <- names(dat3)
    colnames3
    selectInput("independent", "Independent Variable",  colnames3)
    }
})

# graph it!

output$plot <- renderPlot({

    if (is.null(filedata())) {
    # User has not uploaded a file yet
    return(NULL)
        }
    if (is.null(input$dependent)) {
    return(NULL)
        }
    if (is.null(input$independent)) {
    return(NULL)
        }

    dat4 <- filedata()
    if(is.null(input$graphtype) || is.na(input$graphtype)) {
        return()
    }
    if(input$graphtype == "Histogram") {

    # Histogram
    h <- ggplot(dat4) +
    geom_histogram(aes(input$dependent, ..density..)) + 
    geom_density(aes(input$dependent, ..density..)) +
    geom_rug(aes(input$dependent))
    print(h)

    } else if(input$graphtype == "Box plot") {

    #Boxplot
    b <- ggplot(dat4,aes(factor(input$independent), input$dependent)) +
    geom_point() + geom_boxplot()
    print(b)

    } else if(input$graphtype == "Bar chart") {

    #Bar chart
    bc <- ggplot(dat4, aes(factor(input$independent), input$dependent)) +
    geom_bar(stat="identity") +
    scale_fill_grey(start = 0, end = 1)
    print(bc)

    } else if(input$graphtype == "Line chart") {

    #Line chart
    lc <- ggplot(dat4, aes(input$independent, input$dependent)) + 
    geom_line()
    print(lc)

    } else {

    #Scatterplot
    sp <- ggplot(dat4, aes(input$independent, input$dependent),
    size=2, position = position_jitter(x = 2,y = 2)) + 
    geom_point(color=alpha("black", 0.15))+
    geom_smooth(method=lm)
    print(sp)

    }

})  
})



shinyApp(ui = ui, server = server)

This code runs with no error but I plots aren't rendering (or not correctly). I am very new to Shiny so I likely am NOT using best practices...still learning those.

If anyone could help me make these plots work, I'd be grateful!

Thanks,

Jen

UPDATE:

OK, so here is the trace log.

SEND {"config":{"workerId":"","sessionId":"e4e72e6aa0974cbe9783d5d88293cca1"}}
RECV {"method":"init","data":{"datafile:shiny.file":null,".clientdata_output_desc_hidden":false,".clientdata_output_sum_hidden":false,".clientdata_output_graphtype_hidden":true,".clientdata_output_dependent_hidden":true,".clientdata_output_independent_hidden":true,".clientdata_output_plot_hidden":true,".clientdata_pixelratio":1,".clientdata_url_protocol":"http:",".clientdata_url_hostname":"127.0.0.1",".clientdata_url_port":"3655",".clientdata_url_pathname":"/",".clientdata_url_search":"",".clientdata_url_hash_initial":"",".clientdata_singletons":"",".clientdata_allowDataUriScheme":true}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"desc","status":"recalculating"}}
SEND {"recalculating":{"name":"desc","status":"recalculated"}}
SEND {"recalculating":{"name":"sum","status":"recalculating"}}
SEND {"recalculating":{"name":"sum","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"sum":"Length  Class   Mode \n     0   NULL   NULL ","desc":" NULL"},"inputMessages":[]}
RECV {"method":"uploadInit","args":[[{"name":"bcl_prices.csv","size":757242,"type":"application/vnd.ms-excel"}]],"tag":0}
SEND {"response":{"tag":0,"value":{"jobId":"91d0c607615b329d2179e868","uploadUrl":"session/e4e72e6aa0974cbe9783d5d88293cca1/upload/91d0c607615b329d2179e868?w="}}}
RECV {"method":"uploadEnd","args":["91d0c607615b329d2179e868","datafile"],"tag":1}
SEND {"progress":{"type":"binding","message":{"id":"desc"}}}
SEND {"busy":"busy"}
SEND {"progress":{"type":"binding","message":{"id":"sum"}}}
SEND {"response":{"tag":1,"value":null}}
SEND {"recalculating":{"name":"desc","status":"recalculating"}}
SEND {"recalculating":{"name":"desc","status":"recalculated"}}
SEND {"recalculating":{"name":"sum","status":"recalculating"}}
SEND {"recalculating":{"name":"sum","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"sum":"  PRODUCT_TYPE_NAME            PRODUCT_CLASS_NAME\n LIQUOR    :6132    BEER                : 683    \n NON LIQUOR:  12    CULINARY PRODUCTS   :   1    \n                    DE-ALCOHOLIZED BEER :   3    \n                    DE-ALCOHOLIZED WINE :   8    \n                    REFRESHMENT BEVERAGE: 111    \n                    SPIRITS             :1147    \n                    WINE                :4191    \n                          PRODUCT_SUB_CLASS_NAME\n TABLE WINE                          :3775      \n BEER                                : 683      \n SCOTCH WHISKY                       : 258      \n SPARKLING WINE                      : 226      \n APERITIF  DESSERT AND FORTIFIED WINE: 180      \n LIQUEURS                            : 169      \n (Other)                             : 853      \n         PRODUCT_MINOR_CLASS_NAME           PRODUCT_COUNTRY_ORIGIN_NAME\n TABLE WINE RED      :2564        CANADA                  :1375        \n TABLE WINE WHITE    :1119        FRANCE                  :1357        \n BEER                : 689        UNITED STATES OF AMERICA: 707        \n SCOTCH - MALT       : 208        ITALY                   : 570        \n SPARKLING WINE WHITE: 181        AUSTRALIA               : 367        \n REGULAR VODKA       : 141        UNITED KINGDOM          : 345        \n (Other)             :1242        (Other)                 :1423        \n PRODUCT_SKU_NO                                    PRODUCT_LONG_NAME\n Min.   :    18   COLUMBIA - KOKANEE CAN                    :   7   \n 1st Qu.:180584   BACARDI - SUPERIOR WHITE                  :   6   \n Median :390374   BAILEYS - ORIGINAL IRISH CREAM            :   6   \n Mean   :417884   CROWN ROYAL                               :   6   \n 3rd Qu.:637145   GREY GOOSE                                :   6   \n Max.   :989319   JACK DANIEL'S - OLD #7 TENNESSEE SOUR MASH:   6   \n                  (Other)                                   :6107   \n PRODUCT_BASE_UPC_NO PRODUCT_LITRES_PER_CONTAINER PRD_CONTAINER_PER_SELL_UNIT\n Min.   :4.068e+07   Min.   : 0.0300              Min.   : 1.00              \n 1st Qu.:5.507e+11   1st Qu.: 0.7500              1st Qu.: 1.00              \n Median :8.088e+11   Median : 0.7500              Median : 1.00              \n Mean   :2.782e+12   Mean   : 0.8481              Mean   : 1.63              \n 3rd Qu.:5.010e+12   3rd Qu.: 0.7500              3rd Qu.: 1.00              \n Max.   :9.501e+12   Max.   :18.0000              Max.   :30.00              \n NA's   :68                                                                  \n PRODUCT_ALCOHOL_PERCENT CURRENT_DISPLAY_PRICE SWEETNESS_CODE   \n Min.   : 0.01           Min.   :    1.49      Min.   : 0.0000  \n 1st Qu.:12.40           1st Qu.:   14.99      1st Qu.: 0.0000  \n Median :13.50           Median :   24.99      Median : 0.0000  \n Mean   :17.14           Mean   :  141.23      Mean   : 0.6654  \n 3rd Qu.:14.50           3rd Qu.:   62.97      3rd Qu.: 0.0000  \n Max.   :75.50           Max.   :30250.00      Max.   :10.0000  \n                         NA's   :1             NA's   :1813     ","desc":"'data.frame':\t6144 obs. of  13 variables:\n $ PRODUCT_TYPE_NAME           : Factor w/ 2 levels \"LIQUOR\",\"NON LIQUOR\": 1 1 1 1 1 1 1 1 1 1 ...\n $ PRODUCT_CLASS_NAME          : Factor w/ 7 levels \"BEER\",\"CULINARY PRODUCTS\",..: 7 7 7 7 7 7 7 7 7 6 ...\n $ PRODUCT_SUB_CLASS_NAME      : Factor w/ 30 levels \"AMERICAN WHISKY\",..: 27 27 27 27 27 27 27 27 27 17 ...\n $ PRODUCT_MINOR_CLASS_NAME    : Factor w/ 85 levels \"ALMOND\",\"AMBER\",..: 77 79 77 79 77 77 77 79 79 43 ...\n $ PRODUCT_COUNTRY_ORIGIN_NAME : Factor w/ 64 levels \"ANTIGUA AND BARBUDA\",..: 10 10 10 10 62 19 10 10 10 29 ...\n $ PRODUCT_SKU_NO              : int  198267 305375 53017 215525 168971 234559 492314 587584 100925 10157 ...\n $ PRODUCT_LONG_NAME           : Factor w/ 5575 levels \"1573  NATIONAL CELLAR - LUZHOU LAOJIAO CO.\",..: 1768 1993 4851 3265 5534 2897 4526 4847 2225 2682 ...\n $ PRODUCT_BASE_UPC_NO         : num  4.82e+10 4.82e+10 5.90e+10 7.80e+11 8.13e+10 ...\n $ PRODUCT_LITRES_PER_CONTAINER: num  3 4 4 4 3 4 16 4 0.75 0.75 ...\n $ PRD_CONTAINER_PER_SELL_UNIT : int  1 1 1 1 1 1 1 1 1 1 ...\n $ PRODUCT_ALCOHOL_PERCENT     : num  14 11.5 12 11 13.5 11 12.5 12 11.5 40 ...\n $ CURRENT_DISPLAY_PRICE       : num  31 33 30 34 37 ...\n $ SWEETNESS_CODE              : int  0 0 0 1 0 0 0 0 0 NA ..."},"inputMessages":[]}
RECV {"method":"update","data":{".clientdata_output_plot_width":989,".clientdata_output_plot_height":400,".clientdata_output_desc_hidden":true,".clientdata_output_sum_hidden":true,".clientdata_output_graphtype_hidden":false,".clientdata_output_dependent_hidden":false,".clientdata_output_independent_hidden":false,".clientdata_output_plot_hidden":false}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"graphtype","status":"recalculating"}}
SEND {"recalculating":{"name":"graphtype","status":"recalculated"}}
SEND {"recalculating":{"name":"dependent","status":"recalculating"}}
SEND {"recalculating":{"name":"dependent","status":"recalculated"}}
SEND {"recalculating":{"name":"independent","status":"recalculating"}}
SEND {"recalculating":{"name":"independent","status":"recalculated"}}
SEND {"recalculating":{"name":"plot","status":"recalculating"}}
SEND {"recalculating":{"name":"plot","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"independent":null,"graphtype":{"html":"<div class=\"form-group shiny-input-container\">\n  <label class=\"control-label\" for=\"graphtype\">Graph Type</label>\n  <div>\n    <select id=\"graphtype\"><option value=\"Histogram\" selected>Histogram</option>\n<option value=\"Boxplot\">Boxplot</option>\n<option value=\"Bar chart\">Bar chart</option>\n<option value=\"Line chart\">Line chart</option>\n<option value=\"Scatterplot\">Scatterplot</option></select>\n    <script type=\"application/json\" data-for=\"graphtype\" data-nonempty=\"\">{}</script>\n  </div>\n</div>","deps":[{"name":"selectize","version":"0.11.2","src":{"href":"shared/selectize"},"meta":null,"script":null,"stylesheet":"css/selectize.bootstrap3.css","head":"<!--[if lt IE 9]>\n<script src=\"shared/selectize/js/es5-shim.min.js\"></script>\n<![endif]-->\n<script src=\"shared/selectize/js/selectize.min.js\"></script>","attachment":null,"all_files":true}]},"plot":{"src":"data:image/png;[base64 data]","width":989,"height":400,"coordmap":[{"domain":{"left":-0.04,"right":1.04,"bottom":-0.04,"top":1.04},"range":{"left":0,"right":989,"bottom":399,"top":-1},"log":{"x":null,"y":null},"mapping":{}}]},"dependent":null},"inputMessages":[]}
RECV {"method":"update","data":{"graphtype":"Histogram"}}
SEND {"progress":{"type":"binding","message":{"id":"dependent"}}}
SEND {"busy":"busy"}
SEND {"progress":{"type":"binding","message":{"id":"independent"}}}
SEND {"recalculating":{"name":"dependent","status":"recalculating"}}
SEND {"recalculating":{"name":"dependent","status":"recalculated"}}
SEND {"recalculating":{"name":"independent","status":"recalculating"}}
SEND {"recalculating":{"name":"independent","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"independent":null,"dependent":{"html":"<div class=\"form-group shiny-input-container\">\n  <label class=\"control-label\" for=\"dependent\">Variable</label>\n  <div>\n    <select id=\"dependent\"><option value=\"PRODUCT_SKU_NO\" selected>PRODUCT_SKU_NO</option>\n<option value=\"PRODUCT_BASE_UPC_NO\">PRODUCT_BASE_UPC_NO</option>\n<option value=\"PRODUCT_LITRES_PER_CONTAINER\">PRODUCT_LITRES_PER_CONTAINER</option>\n<option value=\"PRD_CONTAINER_PER_SELL_UNIT\">PRD_CONTAINER_PER_SELL_UNIT</option>\n<option value=\"PRODUCT_ALCOHOL_PERCENT\">PRODUCT_ALCOHOL_PERCENT</option>\n<option value=\"CURRENT_DISPLAY_PRICE\">CURRENT_DISPLAY_PRICE</option>\n<option value=\"SWEETNESS_CODE\">SWEETNESS_CODE</option></select>\n    <script type=\"application/json\" data-for=\"dependent\" data-nonempty=\"\">{}</script>\n  </div>\n</div>","deps":[{"name":"selectize","version":"0.11.2","src":{"href":"shared/selectize"},"meta":null,"script":null,"stylesheet":"css/selectize.bootstrap3.css","head":"<!--[if lt IE 9]>\n<script src=\"shared/selectize/js/es5-shim.min.js\"></script>\n<![endif]-->\n<script src=\"shared/selectize/js/selectize.min.js\"></script>","attachment":null,"all_files":true}]}},"inputMessages":[]}
RECV {"method":"update","data":{"dependent":"PRODUCT_SKU_NO"}}
SEND {"progress":{"type":"binding","message":{"id":"plot"}}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"plot","status":"recalculating"}}
SEND {"recalculating":{"name":"plot","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"plot":{"src":"data:image/png;[base64 data]","width":989,"height":400,"coordmap":[{"domain":{"left":-0.04,"right":1.04,"bottom":-0.04,"top":1.04},"range":{"left":0,"right":989,"bottom":399,"top":-1},"log":{"x":null,"y":null},"mapping":{}}]}},"inputMessages":[]}
RECV {"method":"update","data":{"dependent":"CURRENT_DISPLAY_PRICE"}}
SEND {"progress":{"type":"binding","message":{"id":"plot"}}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"plot","status":"recalculating"}}
SEND {"recalculating":{"name":"plot","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"plot":{"src":"data:image/png;[base64 data]","width":989,"height":400,"coordmap":[{"domain":{"left":-0.04,"right":1.04,"bottom":-0.04,"top":1.04},"range":{"left":0,"right":989,"bottom":399,"top":-1},"log":{"x":null,"y":null},"mapping":{}}]}},"inputMessages":[]}
RECV {"method":"update","data":{".clientdata_output_desc_hidden":false,".clientdata_output_sum_hidden":false,".clientdata_output_graphtype_hidden":true,".clientdata_output_dependent_hidden":true,".clientdata_output_independent_hidden":true,".clientdata_output_plot_hidden":true}}
RECV {"method":"update","data":{".clientdata_output_desc_hidden":true,".clientdata_output_sum_hidden":true,".clientdata_output_graphtype_hidden":false,".clientdata_output_dependent_hidden":false,".clientdata_output_independent_hidden":false,".clientdata_output_plot_hidden":false}}
RECV {"method":"update","data":{"graphtype":"Boxplot"}}
SEND {"progress":{"type":"binding","message":{"id":"dependent"}}}
SEND {"busy":"busy"}
SEND {"progress":{"type":"binding","message":{"id":"independent"}}}
SEND {"recalculating":{"name":"dependent","status":"recalculating"}}
SEND {"recalculating":{"name":"dependent","status":"recalculated"}}
SEND {"recalculating":{"name":"independent","status":"recalculating"}}
SEND {"recalculating":{"name":"independent","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"independent":{"html":"<div class=\"form-group shiny-input-container\">\n  <label class=\"control-label\" for=\"independent\">Independent Variable</label>\n  <div>\n    <select id=\"independent\"><option value=\"PRODUCT_SKU_NO\" selected>PRODUCT_SKU_NO</option>\n<option value=\"PRODUCT_BASE_UPC_NO\">PRODUCT_BASE_UPC_NO</option>\n<option value=\"PRODUCT_LITRES_PER_CONTAINER\">PRODUCT_LITRES_PER_CONTAINER</option>\n<option value=\"PRD_CONTAINER_PER_SELL_UNIT\">PRD_CONTAINER_PER_SELL_UNIT</option>\n<option value=\"PRODUCT_ALCOHOL_PERCENT\">PRODUCT_ALCOHOL_PERCENT</option>\n<option value=\"CURRENT_DISPLAY_PRICE\">CURRENT_DISPLAY_PRICE</option>\n<option value=\"SWEETNESS_CODE\">SWEETNESS_CODE</option></select>\n    <script type=\"application/json\" data-for=\"independent\" data-nonempty=\"\">{}</script>\n  </div>\n</div>","deps":[{"name":"selectize","version":"0.11.2","src":{"href":"shared/selectize"},"meta":null,"script":null,"stylesheet":"css/selectize.bootstrap3.css","head":"<!--[if lt IE 9]>\n<script src=\"shared/selectize/js/es5-shim.min.js\"></script>\n<![endif]-->\n<script src=\"shared/selectize/js/selectize.min.js\"></script>","attachment":null,"all_files":true}]},"dependent":{"html":"<div class=\"form-group shiny-input-container\">\n  <label class=\"control-label\" for=\"dependent\">Dependent Variable</label>\n  <div>\n    <select id=\"dependent\"><option value=\"PRODUCT_SKU_NO\" selected>PRODUCT_SKU_NO</option>\n<option value=\"PRODUCT_BASE_UPC_NO\">PRODUCT_BASE_UPC_NO</option>\n<option value=\"PRODUCT_LITRES_PER_CONTAINER\">PRODUCT_LITRES_PER_CONTAINER</option>\n<option value=\"PRD_CONTAINER_PER_SELL_UNIT\">PRD_CONTAINER_PER_SELL_UNIT</option>\n<option value=\"PRODUCT_ALCOHOL_PERCENT\">PRODUCT_ALCOHOL_PERCENT</option>\n<option value=\"CURRENT_DISPLAY_PRICE\">CURRENT_DISPLAY_PRICE</option>\n<option value=\"SWEETNESS_CODE\">SWEETNESS_CODE</option></select>\n    <script type=\"application/json\" data-for=\"dependent\" data-nonempty=\"\">{}</script>\n  </div>\n</div>","deps":[{"name":"selectize","version":"0.11.2","src":{"href":"shared/selectize"},"meta":null,"script":null,"stylesheet":"css/selectize.bootstrap3.css","head":"<!--[if lt IE 9]>\n<script src=\"shared/selectize/js/es5-shim.min.js\"></script>\n<![endif]-->\n<script src=\"shared/selectize/js/selectize.min.js\"></script>","attachment":null,"all_files":true}]}},"inputMessages":[]}
RECV {"method":"update","data":{"independent":"PRODUCT_SKU_NO","dependent":"PRODUCT_SKU_NO"}}
SEND {"progress":{"type":"binding","message":{"id":"plot"}}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"plot","status":"recalculating"}}
SEND {"recalculating":{"name":"plot","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"plot":{"src":"data:image/png;[base64 data]","width":989,"height":400,"coordmap":[{"domain":{"left":-0.04,"right":1.04,"bottom":-0.04,"top":1.04},"range":{"left":0,"right":989,"bottom":399,"top":-1},"log":{"x":null,"y":null},"mapping":{}}]}},"inputMessages":[]}
RECV {"method":"update","data":{"dependent":"CURRENT_DISPLAY_PRICE"}}
SEND {"progress":{"type":"binding","message":{"id":"plot"}}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"plot","status":"recalculating"}}
SEND {"recalculating":{"name":"plot","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"plot":{"src":"data:image/png;[base64 data]","width":989,"height":400,"coordmap":[{"domain":{"left":-0.04,"right":1.04,"bottom":-0.04,"top":1.04},"range":{"left":0,"right":989,"bottom":399,"top":-1},"log":{"x":null,"y":null},"mapping":{}}]}},"inputMessages":[]}
RECV {"method":"update","data":{"independent":"PRODUCT_LITRES_PER_CONTAINER"}}
SEND {"progress":{"type":"binding","message":{"id":"plot"}}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"plot","status":"recalculating"}}
SEND {"recalculating":{"name":"plot","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":[],"values":{"plot":{"src":"data:image/png;[base64 data]","width":989,"height":400,"coordmap":[{"domain":{"left":-0.04,"right":1.04,"bottom":-0.04,"top":1.04},"range":{"left":0,"right":989,"bottom":399,"top":-1},"log":{"x":null,"y":null},"mapping":{}}]}},"inputMessages":[]}

Any of it making any sense to anyone (obviously not to me)?

ANOTHER UPDATE:

When I remove the NULL returns I get this error:

Warning: Error in : Aesthetics must be either length 1 or the same as the data (6144): x, y
Stack trace (innermost first):
    110: check_aesthetics
    109: f
    108: l$compute_aesthetics
    107: f
    106: by_layer
    105: ggplot_build
    104: print.ggplot
    103: print
    102: renderPlot [#124]
     92: <reactive:plotObj>
     81: plotObj
     80: origRenderFunc
     79: output$plot
      4: <Anonymous>
      3: do.call
      2: print.shiny.appobj
      1: <Promise>

The code for plotting the histogram has been changed a little to this:

# Histogram
        h <- ggplot(dat4, aes(input$dependent)) +
        geom_histogram(aes(input$dependent), stat="count") + 
        geom_density(aes(input$dependent)) +
        geom_rug(aes(input$dependent))
        print(h)

UPDATE:

After a lot of Googling, my code has changed quite a bit but I keep getting the same error.

Here's the new server code:

options(shiny.browser=TRUE)

server <- shinyServer(function(input, output) {


# First panel - load data and see summary
#This function is repsonsible for loading in the selected file
filedata <- reactive({
        infile <- input$datafile
        if (is.null(infile)) {
    # User has not uploaded a file yet
    return(NULL)
        }
        read.csv(infile$datapath, stringsAsFactors = T)
})  

#This previews the CSV data file
output$desc <- renderPrint({
    str(filedata())
})
    output$sum <- renderPrint({
        dat <- filedata()
        summary(dat)    
    })

# Second panel - choose variables for plotting

# Choose graph type 
output$graphtype <- renderUI({
    grphtp <- c("Histogram", "Boxplot", "Bar chart", "Line chart",  "Scatterplot")
    selectInput("graphtype", "Graph Type", grphtp)
})

# Choose dependent variable, based on graph type
output$dependent <- renderUI({
    if(is.null(input$graphtype) || is.na(input$graphtype)) {
        return()
    }
    dat <- filedata()[,sapply(filedata(), is.numeric)]
    colnames <- names(dat)
    colnames
    if(input$graphtype == "Histogram"){
    selectInput("dependent", "Variable",  colnames)
    } else {
    selectInput("dependent", "Dependent Variable",  colnames)
    }
})

# Choose independent variable, based on graph type
output$independent <- renderUI({
    if(is.null(input$graphtype) || is.na(input$graphtype)) {
        return()
    }
    if(input$graphtype == "Histogram"){
    return(NULL)
    } else { 
    dat <- filedata()
    colnames <- names(dat)
    colnames
    selectInput("independent", "Independent Variable",  colnames)
    }
})

# graph it!

output$plot <- renderPlot({

    if (is.null(filedata())) {
    # User has not uploaded a file yet
    return(NULL)
        }

    #dat4 <- filedata()
    if(is.null(input$graphtype) || is.na(input$graphtype)) {
        return()
    }
    if(input$graphtype == "Histogram") {

    dat <- filedata()[,sapply(filedata(), is.numeric)]
    # Histogram
    h <- ggplot(dat, aes(x=input$dependent)) +
    geom_histogram(aes(input$dependent), stat="density") + 
    geom_density(aes(input$dependent, ..density..)) +
    geom_rug(aes(input$dependent))
    print(h)

    } else if(input$graphtype == "Box plot") {

    dat <- filedata()
    #Boxplot
    b <- ggplot(dat,aes(x=factor(input$independent), y=input$dependent)) +
    geom_point() + geom_boxplot()
    print(b)

    } else if(input$graphtype == "Bar chart") {

    dat <- filedata()
    #Bar chart
    bc <- ggplot(dat, aes(x=factor(input$independent), y=input$dependent)) +
    geom_bar(stat="identity") +
    scale_fill_grey(start = 0, end = 1)
    print(bc)

    } else if(input$graphtype == "Line chart") {

    dat <- filedata()
    #Line chart
    lc <- ggplot(dat, aes(x=input$independent, y=input$dependent)) + 
    geom_line()
    print(lc)

    } else {

    dat <- filedata()
    #Scatterplot
    sp <- ggplot(dat, aes(x=input$independent, y=input$dependent),
    size=2, position = position_jitter(x = 2,y = 2)) + 
    geom_point(color=alpha("black", 0.15))+
    geom_smooth(method=lm)
    print(sp)

    }

})  
})

And the new trace is attached gives the same error as above. I'd paste the whole thing but I run out of space. If anyone wants to see it I can paste in as a response below.

It all seems to revolve around aesthetics length. I thought it was because I was subsetting in the wrong spot and introducing vectors into x and y. I must still be doing that but I can't see where.

Upvotes: 1

Views: 3101

Answers (1)

Bishops_Guest
Bishops_Guest

Reputation: 1472

I highly recommend using the RStudio IDE. It will make your life much simpler.

I do not have time to fully debug this for you, but I do see a few issues, and will recommend some better practices.

  1. in output$plot, you have if (is.null(input$independent)) { ...}. For your histogram this is triggering every time because input$independent is not defined when the histogram method is selected.
  2. When using ggplot() define your aesthetics in the ggplot() statement. It makes your code less messy. In this case you also need to use aes_string() because ggplot uses non-conventional evaluation. For example for your histogram: ggplot(dat4,aes_string(x=input$dependent)) + geom_histogram(bins=50) + ...

As for better practices:

  1. When you are making such a complex app break it into much more manageable small parts. Test each one independently before trying to fit it into the whole.
  2. Seperate your ui and server into two separate files called ui.R and server.R. Then instead of loading up a ui and server R object to pass to shiny, use runApp() while your ui and server files are in your working directory to start the app. (the RStudio IDE makes this easy)
  3. You can then use browser() to switch to command line at a specific point in your app to take a look and make sure it is running properly.

Upvotes: 3

Related Questions