Smiley presentation

Jiddu Alexander
(tomorrow)

The Smile

Smile

Smile

It may not be the happiest smile, but in Shiny it is a very interactive smile.

Actually it is not a smiley, it is a plot generated by ggplot2.

In the next few slides we'll go through the code to generate the basic smiley, followed by the Shiny ui.R and server.R scripts.

jiddualexander.shinyapps.io/smiley/

The Code - Basics

The plot is generated from 4 shapes. Three circles and a rectangle. For the circles we use the circles function as you see on the left. The rectangle is initialised by hand.

circles <- function(center = c(0,0),diameter = 1, npoints = 100){
  r = diameter / 2
  tt <- seq(0,2*pi,length.out = npoints)
  xx <- center[1] + r * cos(tt)
  yy <- center[2] + r * sin(tt)
  data.frame(x = xx, y = yy)
}
theHead <- circles(c(0,0),2,npoints = 100)
plot(theHead)

plot of chunk unnamed-chunk-1

For the plot geom_polygon and geom_path are called for each shape and theme_void() to omit the grid and axis.

g <- ggplot() 
g <- g + geom_polygon(data = theHead, aes(x,y), fill = "yellow")
g <- g + geom_path(data = theHead, aes(x,y))

The Code - ui.R

The user interface is split in three parts. Header, sidebar and main panel.

The sidebars contains 4 user inputs. A radiobutton to change the colour, and 3 sliders to change the positions of the eyes, and the size of the mouth.

shinyUI(pageWithSidebar(
  headerPanel("Welcome to GGPLOT Smiley"),
  sidebarPanel(
    radioButtons(inputId = "colour", ...
    sliderInput(inputId = "leftEye", ...
    sliderInput(inputId = "rightEye",...
    sliderInput(inputId = "mouth", la...
  ),
  mainPanel(
    plotOutput("smiley")
  )
))

The Code - server.R

For any change the complete plot has to be redone, but not all code is evaluated each time. The circle function and head circle are set outside the function. Then, for each eye and the mouth there is a reactive function that is evaluated when necessary.

leftEye <- reactive({
  leftEye = circles(c(-input$leftEye,input$leftEye),0.4,npoints = 100)
})

Lastly, the renderplot takes care of the colour with an if and else statement.

output$smiley <- renderPlot({
(...)
if(input$colour == "red"){
  g <- g + geom_polygon(data = theHead, aes(x,y), fill = "red")
}
(...)
})