laoisman
laoisman

Reputation: 61

shiny: plotting selected columns from dataset to graphs

Just discovering shiny apps but this is driving me insane.......I have looked at numerous examples of server.R and ui.R code and cannot figure out what I am doing wrong. Apologies in advance if it's something very basic..........

Taking the iris dataset as an example, I want to plot one column against another, something simple using qplot or preferably ggplot

However, using qplot I get this: qplot output

and using ggplot2, I get the error: ggplot output

I don't think I need the reactive function as I'm not subsetting the dataset, just extracting columns to plot.

server.R code

library(shiny)
library(shinyapps)
library(ggplot2)

shinyServer(function(input, output, session) {

    output$text1 <- renderText({input$id1})

    output$text2 <- renderText({input$select1})

    output$plot1 <- renderPlot({
            g <- qplot(Sepal.Length, input$select1, data = iris)
            print(g)
    })

})

or using ggplot function to replace the qplot call

            g <- ggplot(iris, aes(x = Sepal.Length, y = input$select1)) 
            g <- g + geom_line(col = "green", lwd =1) + 
                    labs(x = "Date", y = "Ranking") + 
                    theme_bw() + scale_y_reverse()

ui.R code

library(shiny)
library(shinyapps)
data(iris)
opts <- unique(colnames(iris))
opts <- opts[-1] ## want to keep Sepal.Length as the x values

shinyUI(pageWithSidebar(
    headerPanel('test with iris database'),
    sidebarPanel(
            selectInput(inputId = "select1", label = "select", 
                        choices = opts),
            textInput(inputId = "id1", label = "Input Text", "")
    ),
    mainPanel(
            p('Output text1'),
            textOutput('text1'),
            textOutput('text2'),
            plotOutput('plot1')
    )
))

Upvotes: 2

Views: 4004

Answers (1)

cdeterman
cdeterman

Reputation: 19960

Change your aes statement to aes_string and make x a string. This should fix the problem.

g <- ggplot(iris, aes_string(x = "Sepal.Length", y = input$select1)) 
g <- g + geom_line(col = "green", lwd =1) +
     labs(x = "Date", y = "Ranking") + 
     theme_bw() + scale_y_reverse()

Upvotes: 5

Related Questions