# Hands-On Tutorial: Shiny Webapp[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#hands-on-tutorial-shiny-webapp "Permalink to this headline")

In this tutorial, we’ll create a simple Shiny webapp in Dataiku. It’s a scatter plot on Haiku T-shirt sales data, similar to the data used in the Basics tutorials.

## Let’s Get Started[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#let-s-get-started "Permalink to this headline")

### Prerequisites[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#prerequisites "Permalink to this headline")

* Some familiarity with R.

### Technical Requirements[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#technical-requirements "Permalink to this headline")

* An instance of Dataiku DSS - version 8.0 or above (note that Dataiku Online is *NOT* compatible with this tutorial);

* An R code environment that has the shiny, dplyr, and magrittr packages.

Tip

You can use the DSS builtin R environment, which has all of the aforementioned packages.

### Webapp Overview[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#webapp-overview "Permalink to this headline")

We will create a webapp which displays a scatter plot showing the total number of item orders by customer age. To make it interactive, we will add a dropdown menu to filter on item category, as well as a slider to filter on age.

The finished webapp is shown below.

## Create Your Project[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#create-your-project "Permalink to this headline")

Create your project by selecting one of these options:

### Import a Starter Project[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#import-a-starter-project "Permalink to this headline")

From the Dataiku homepage, click **+New Project > DSS Tutorials > Developer > Visualization (Tutorial)**.

Note

You can also download the starter project from this website and import it as a zip file.

### Continue From the Previous Hands-On Tutorial[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#continue-from-the-previous-hands-on-tutorial "Permalink to this headline")

If you are following the Academy Visualization course and have already completed one of the previous hands-on lessons, you can begin this lesson by continuing with the same project you created earlier.

### Download and Import Dataset Into New Project[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#download-and-import-dataset-into-new-project "Permalink to this headline")

Alternatively, you can download the Orders\_enriched\_prepared dataset and import it into a new project.

## Create a New Shiny Webapp[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#create-a-new-shiny-webapp "Permalink to this headline")

Create a new empty Shiny webapp:

* In the Code menu of the top navigation bar, select **Webapps**.

* Click **+ New Webapp > Code Webapp**

* Select **Shiny > An empty Shiny app**

* Provide a simple name for the webapp, such as `shiny webapp`, and click **Create**.

You will be redirected to the webapp editor.

## Explore the Webapp Editor[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#explore-the-webapp-editor "Permalink to this headline")

The Shiny webapp editor is divided into two panes.

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

* A *UI* tab that contains the code that defines the layout of the webapp, 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 webapp.

The right pane gives you several views on the webapp.

* 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.

* The **Settings** tab allows you to set the code environment for this webapp, if you want it to be different from the project default.

* After exploring the webapp editor, click **Start Backend** to activate the backend and proceed to building the webapp.

## Code the Webapp[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#code-the-webapp "Permalink to this headline")

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 webapp.

### Define the UI[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#define-the-ui "Permalink to this headline")

* In the UI tab, insert the following code to define the layout for the webapp:

§ library(shiny)

§ # Define UI for application that draws a histogram

§ shinyUI(fluidPage(

§ # Application title

§ titlePanel("Order total by Customer age"),

§ # Webapp layout

§ sidebarLayout(

§ sidebarPanel(),

§ # Show a plot of the generated distribution

§ mainPanel(

§ plotOutput("scatterPlot")

§ )

§ )

§ ))

In the above piece of code:

* We indicate that we are using the `shiny` R library;

* The shinyUI() function indicates we’re building the UI for the webapp;

* 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.

* `titlePanel()` creates a title at the top of the webapp

* `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.

### Define the Visualization[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#define-the-visualization "Permalink to this headline")

* 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 scatter plot with the specified

§ plot(as.numeric(df$age), as.numeric(df$total), ylab="Order total", xlab="Customer age")

§ })

§ })

In the above piece of code:

* We are using the `shiny`, `dplyr`, `magrittr`, and `dataiku` R libraries;

* To incorporate Dataiku datasets into Shiny webapps, we simply use the `dkuReadDataset()` function to pull the dataset as an R data frame, as you would in an R recipe or notebook;

* The `shinyServer()` function indicates we’re building the server logic for the webapp.

* 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.

* Click **Save**.

The preview should now show the current (non-interactive) scatter plot.

### Add Interactivity[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#add-interactivity "Permalink to this headline")

The current scatter plot 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, replace `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 data frame `df` and uses the widget selections to filter the data frame to only use records with the correct order year and t-shirt category. It then defines the x and y axes of the scatter plot to be the age and order total from the filtered data frame.

* Save your work and refresh the preview.

It should now show the current interactive scatter plot.

## Publish the Webapp on a Dashboard[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#publish-the-webapp-on-a-dashboard "Permalink to this headline")

When you are done with editing, you can easily publish your webapp on a dashboard.

* Click **Actions** in the top-right corner of the screen.

* From the **Actions** menu, click **Publish**.

* Select the dashboard and slide you wish to publish your webapp on.

* Click **Create**.

## What’s Next?[¶](https://knowledge.dataiku.com/latest/courses/advanced-code/visualization/shiny-hands-on.html#what-s-next "Permalink to this headline")

Using Dataiku DSS, you have created an interactive Shiny webapp and published it to a dashboard. To go further:

* You can examine a version of this sample webapp on the Dataiku gallery;

* See the reference doc for further details on using Shiny in Dataiku;

* See the Shiny gallery (external) for further inspiration on what is possible in Shiny webapps.
