Cameron G
10/6/17
This Shiny web app takes the “iris” data set in R and displays the relationship between sepal length and width for a species designated by the user. The data contains information on 3 species: setosa, versicolor, and virginica. A summary of the relevant variables for all species types is shown below.
data(iris)
summary(iris$Sepal.Length)
Min. 1st Qu. Median Mean 3rd Qu. Max.
4.300 5.100 5.800 5.843 6.400 7.900
summary(iris$Sepal.Width)
Min. 1st Qu. Median Mean 3rd Qu. Max.
2.000 2.800 3.000 3.057 3.300 4.400
The ui.R code shows that the user is prompted to make two choices that generate reactive output in a scatter plot.
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Comparing Iris Species"),
sidebarPanel(
selectInput("variable","Select a Species:",
list("setosa" = "setosa",
"versicolor" = "versicolor",
"virginica" = "virginica",
"all species" = "all species")),
checkboxInput("trendline","Show trendline",value=TRUE)
),
mainPanel(
h3('Sepal Length and Width'),
plotOutput("irisPlot")
)
))
The server.R code generates a graph of sepal length vs. sepal width for the species specified by the user in input$variable, and generates one of two graphs depending whether the user selects to add a trendline.
shinyServer(
function(input,output){
formulaText <- reactive(function(){
paste("Sepal.Length ~", input$variable)
})
output$caption <- reactiveText(function() {
formulaText()
})
output$irisPlot <- reactivePlot(function() {
if (input$variable == "setosa") {
iris_data <- iris[iris$Species=="setosa",]
col = "#999999"
}
else if (input$variable == "versicolor") {
iris_data <- iris[iris$Species=="versicolor",]
col="#E69F00"
}
else if (input$variable == "virginica") {
iris_data <- iris[iris$Species=="virginica",]
col="#56B4E9"
}
else if (input$variable == "all species") {
iris_data <- iris
col=c("#999999", "#E69F00", "#56B4E9")
}
p <- ggplot(iris_data, aes(Sepal.Length,Sepal.Width)) + geom_point(aes(color=Species)) + scale_color_manual(values=col) + coord_cartesian(ylim=c(2,4.5),xlim=c(4,8)) + theme(legend.position="top") + geom_smooth(method="lm",color="black")
p2 <- ggplot(iris_data, aes(Sepal.Length,Sepal.Width)) + geom_point(aes(color=Species)) + scale_color_manual(values=col) + coord_cartesian(ylim=c(2,4.5),xlim=c(4,8)) + theme(legend.position="top")
ifelse(input$trendline,print(p),print(p2))
})
})
The following plot is what is displayed when “all species” is selected from the dropdown menu and the checkbox for “show trendline” is selected.