3lli0t
3lli0t

Reputation: 77

Shiny Correlation Plot

I'm trying to build a simple Shiny app, using USArrests database, that shows the correlation between density population and the 3 variables of crimes (Murder, Assault, Rape), changing the crime variables with selectInpuct.

Here the code of ui.R:

 shinyUI(fluidPage(
    titlePanel("Violent Crime Rates by US State"),

    sidebarLayout(
        sidebarPanel(
            helpText("A series of plots that display correlation between density population and various kind of crimes"),

            selectInput("var", 
                        label = "Choose a crime",
                        choices = c("Murder"=1, "Assault"=2,
                                       "Rape"=4),
                        selected = "Murder")


            ),

        mainPanel(plotOutput('crimeplot'))
    )
))

and the server.R

shinyServer(function(input,output){


output$crimeplot<- renderPlot({
    x<-as.numeric(input$var)
    y<-as.numeric(USArrests$UrbanPop)

    plot(x, y, log = "xy")




})

}

but running the app it returns:

ERROR: 'x' and 'y' lengths differ

Could you help me, and explain what's wrong with what I am doing?

Thank you very much in advance!

Upvotes: 2

Views: 3288

Answers (1)

ekstroem
ekstroem

Reputation: 6191

I fould a couple of small errors that I have fixed in the code below.

  • Your selection returns the column number (as a string) and you need to convert it to a number and extract the relevant column from the data frame in server.R.
  • The default value of selected in ui.R should be the starting value and not the label.

The updated server.R looks as follows

shinyServer(function(input,output){
                output$crimeplot<- renderPlot({
                    x<-as.numeric(USArrests[,as.numeric(input$var)])
                    y<-as.numeric(USArrests$UrbanPop)
                    plot(x, y, log = "xy", xlab=colnames(USArrests)[as.numeric(input$var)], ylab="Urban Pop")
                })
            })

and ui.R looks like this:

shinyUI(fluidPage(
    titlePanel("Violent Crime Rates by US State"),    
    sidebarLayout(
        sidebarPanel(
            helpText("A series of plots that display correlation between density population and various kind of crimes"),

            selectInput("var",
                        label = "Choose a crime",
                        choices = c("Murder"=1, "Assault"=2,
                            "Rape"=4),
                        selected = 1)
            ),

        mainPanel(plotOutput('crimeplot'))
        )
    ))

Upvotes: 1

Related Questions