howto

Shiny Web Apps

Applies to DSS 4.1 and above | December 07, 2017

In Dataiku DSS, web apps provide a way to create interactive visualizations that can be shared on dashboards for sophisticated reporting. You can create web apps with HTML/Javascript, Python Bokeh, or R Shiny.

In this post, we’ll create a simple Shiny web app in Dataiku DSS. It’s a simple scatterplot on Haiku T-shirt sales data, related to the data used in the Tutorials.

Prerequisites

You will need:

  • The Orders_enriched_prepared dataset. This can be found in the project DSS Tutorials > Automation > Deployment or you can download the data and import it into a new project.
  • An R code environment with the shiny, dplyr, and magrittr packages.

Creating a New Shiny Webapp

Create a new empty Shiny web app:

  1. In the top navigation bar, select Lab - Notebooks > Web apps
  2. Click + New Web App
  3. Select Shiny
  4. Choose An empty Shiny app and type a name for the web app

Notebook/Webapps navigation bar with arrows on: 1. Lab - notebooks icon, 2.webapps.

You will be redirected to the web app editor. ## The Web App Editor

The Shiny web app editor is divided into two panes.

Shiny web app editor; empty

The left pane allows you to see and edit the R code underlying the web app, and contains two tabs:

  • A UI tab that contains the code that defines the layout of the web app, defines and displays interactive widgets, and displays the visualization generated in the Server tab.
  • A Server tab that defines the server logic required to create the visualization. It accesses the data, uses the selections in the widgets on the UI tab as input, and creates the output to be displayed in the web app.

The right pane gives you several views on the web app.

  • The Preview tab allows you to write and test your code in the left pane while having immediate visual feedback in the right pane. At any time you can save or reload your current code by clicking on the Save button or the Reload Preview button.
  • The UI and Server tabs allow you to look at different portions of the code side-by-side in the left and right panes.
  • The Log is useful for troubleshooting problems.
  • Settings allows you to set the code environment for this web app, if you want it to be different from the project default.

Coding the Web App

While the code is split across two files, and there is no explicit code needed to listen for changes to the widget values, the concepts behind Shiny and Bokeh are very similar.

Let’s build the code behind the R Shiny web app.

Defining the UI

In the UI tab, insert the following code to define the layout for the web app.

library(shiny)

# Define UI for application that draws a histogram
shinyUI(fluidPage(

  # Application title
  titlePanel("Order total by Customer age"),

  # Web app layout
  sidebarLayout(

    sidebarPanel(),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("scatterPlot")
    )
  )
))
  • We are using the shiny R library
library(shiny)
  • The shinyUI() function indicates we’re building the UI for the web app
  • The fluidPage() function allows us to define a flexible layout for the page. It accepts several arguments that are the components of the page layout.
shinyUI(fluidPage(

titlePanel() creates a title at the top of the web app

  titlePanel("Order total by Customer age"),

sidebarLayout() defines a layout where widgets are defined in a sidebar panel, and the visualization is displayed in a main panel. For now, we’ll leave sidebarPanel() empty and just include the definition for the mainPanel(), which will show plotOutput() as defined by the scatterPlot element of the output object. We’ll add the interactivity later.

  sidebarLayout(
    sidebarPanel(),
    mainPanel(
      plotOutput("scatterPlot")
    )
  )

Defining the Visualization

Now, in the Server tab, insert the following code to define the output visualization.

library(shiny)
library(dplyr)
library(magrittr)
library(dataiku)

df <- dkuReadDataset("Orders_enriched_prepared", samplingMethod="head", nbRows=100000)

# Define server logic required to draw a plot
shinyServer(function(input, output) {

  # Expression that generates a plot. The expression is
  # wrapped in a call to renderPlot to indicate that:
  #
  #  1) It is "reactive" and therefore should re-execute automatically
  #     when inputs change
  #  2) Its output type is a plot

  output$scatterPlot <- renderPlot({

    # draw the scatterplot with the specified
    plot(as.numeric(df$age), as.numeric(df$total), ylab="Order total", xlab="Customer age")
  })
})
  • We are using the shiny, dplyr, magrittr, and dataiku R libraries
library(shiny)
library(dplyr)
library(magrittr)
library(dataiku)
  • To incorporate Dataiku datasets into Shiny web apps, simply use the dkuReadDataset function to pull the dataset as an R dataframe, as you would in an R recipe or notebook.
df <- dkuReadDataset("Orders_enriched_prepared", samplingMethod="head", nbRows=100000)
  • The shinyServer() function indicates we’re building the server logic for the web app.
shinyServer(function(input, output) {
  • The renderPlot() function contains the code to generate the output visualization. It can also accept input from widgets in the UI code; we will add the interactivity in a moment. The results of renderPlot() are saved to the scatterPlot element of the output object, which is then displayed in the Preview.
  output$scatterPlot <- renderPlot({
    plot(as.numeric(df$age), as.numeric(df$total), ylab="Order total", xlab="Customer age")
  })

Save your work, and the preview should show the current (non-interactive) scatterplot.

Non-interactive Shiny web app

Adding Interactivity

The current scatterplot includes all orders from 2013-2017, across all types of t-shirts sold. Now let’s add the ability to select a subset of years, and a specific category of t-shirt. To do this, we need to make changes to the UI and Server code.

In the UI tab, change sidebarPanel() to the following.

    sidebarPanel(
      sliderInput("year", "Order year", 2013, 2017, value = c(2013, 2017)),
      selectInput("category", "T-shirt category",
          c("All","White T-Shirt M","White T-Shirt F","Black T-Shirt M",
            "Black T-Shirt F","Hoodie","Tennis Shirt")
      )
    ),
  • The sliderInput() function creates a slider widget labeled “Order year”, that has values ranging from 2013 to 2017, and an initial state where all years are selected. The widget selection is saved to the year element of the input object.
  • The selectInput() function creates a dropdown selection widget labeled “T-shirt category”, that has values for each of the t-shirt categories plus “All”. The widget selection is saved to the category element of the input object.

In the Server tab, change renderPlot() as follows.

  output$scatterPlot <- renderPlot({
      df %>% filter(order_date_year >= input$year[1]) %>%
             filter(order_date_year <= input$year[2]) -> selected
      if ( input$category != "All" ) {
          selected <- filter(selected,tshirt_category == input$category)
      }

    x  <- as.numeric(selected$age)
    y  <- as.numeric(selected$total)

    # draw the histogram with the specified number of bins
    plot(x, y, ylab="Order total", xlab="Customer age")
  })

This takes the input dataframe df and uses the widget selections to filter the dataframe to only use records with the correct order year and t-shirt category. It then defines the x and y axes of the scatterplot to be the age and order total from the filtered dataframe.

Save your work, refresh the preview, and it should now show the current interactive scatterplot.

Interactive Shiny web app

Publish to a Dashboard

When you are done with editing, you can easily publish your web app on a dashboard from the Actions dropdown at the top-right corner of the screen.

Webapps editor window with the actions drop-down menu opened and arrow on publish

What’s Next

Using Dataiku DSS, you have created an interactive Shiny web app and published it to a dashboard.

You can examine a version of this sample web app on the Dataiku gallery.

For further inspiration on what is possible in Shiny web apps, see the Shiny gallery (external).