Plotly : Advanced plots and features

Plotly is a d3 based graphing library used to produce interactive and high quality graphs in R. In the following exercises, we will look at some advanced plots and features avaialable in the package. Please note that the list here is not exhaustive.
We will use datasets available in base R packages.

You are expected to have the knowledge of generating basic plots using plotly package before attempting this exercise set. It is recommended that you go through this exercise set to test your knowledge on plotly basics.

Answers to the exercises are available here.

Refer to this link for more help on the plotly functions.
For a quick info on the functions and arguments required to build basic plotly plots, refer to this cheat sheet.

Learn more about Plotly in Section 17 Interactive Visualizations with Plotly of the online course Data Science and Machine Learning Bootcamp with R.

Exercise 1

Install and load the latest version of plotly package.

Generate separate histograms for the first four columns of iris dataset and save the plots in objects p1, p2, p3 and p4.
HINT: Use plot_ly() function with x argument and type="histogram". Use name argument to give appropriate name for the trace.

Exercise 2

a. Use subplot() function to generate a plot with all the plot objects from previous exercise as the arguments.

b. Use the nrows argument to arrange 2 plots per row.

Exercise 3

a. Generate a scatter plot for the iris dataset with first column on the x-axis and second column on the y-axis. Save the plot object.

b. Generate a 2d histogram using the add_histogram2d() function.Save the plot object.
HINT: Use the function plot_ly() with the same x and y arguments and pass the plot object to the 2-d histogram function.

Exercise 4

Generate a subplot with the scatter plot and the 2-d histogram created in the previous exercise.

Notice how the scatter plot can be represented in a more interesting way. Cells in the 2-d histogram are binned and represented with the color on the scale based on the cell population/density.

Exercise 5

Set the value of shareX and shareY arguments in the subplot() function to scale the plots to the same range of x and y.

Exercise 6

Now, let us build a 3-d surface plot. The syntax to build such plot is as below.
plot_ly(z = matrix(1:100, nrow = 10)) %>% add_surface()
Click, hold and drag the cursor to see the plot surface.

Build a 3-d surface plot using the volcano dataset available in the base R distribution.

Exercise 7

Let’s look at few helpful and commonly used arguments from the layout() function.

Create and save a scatter plot object with first and second columns of iris dataset as x and y arguments respectively. Colour the markers based on the species

Exercise 8

a. Add an appropriate title to the plot using the layout function and title argument.
b. Add an appropriate x-axis label using the xaxis argument. xaxis takes a list of attribute values. Refer to the R reference page for more help.
c. Add an appropriate y-axis label.

Exercise 9

a. Use the range attribute in the list of values given to the xaxis argument to set the x-axis range from 1 to 10.
b. Similarly, set the y-axis range from 1 to 5.

Exercise 10

Try different layout options to further customize the font, axes etc… of the plot.




Getting started with Plotly: basic Plots

Plotly is a d3 based graphing library used to produce interactive and high quality graphs in R. In the following exercises, we will look at the basic plots’ syntax and some basic features in the plotly functions.
We will use datasets available in base R packages.

Refer to the documentation of the plotly packages when in need of help with the functions and arguments.
Also, refer to this link for figure references

Installation of the package is straight-forward as it is available on CRAN.
Use this command install.packages(‘plotly’) to install the package. Do not forget to load the package before trying out the exercises.

Answers to the exercises are available here.

Learn more about Plotly in Section 17 Interactive Visualizations with Plotly of the online course Data Science and Machine Learning Bootcamp with R.

Exercise 1

a. Generate a histogram for the first column of iris dataset using the plot_ly() function.
For the first run, supply only one argument to the function and see the message it returns.
identify the argument that you need to include to specify a chart type.

Exercise 2

Identify the argument to specify number of bins and generate a histogram with 20 bins using the same data.

Notice the behaviour of plot on mouse hover. There are also a few options available on the right top corner of the plot to zoom, save the plot etc.

Exercise 3

a. Generate a scatter plot for the first two columns of the iris dataset. Identify and use the appropriate arguments to get the plot with first column on the x axis and second column on y axis.
b. Using the color argument, specify the color such that data points are colored based on the Species column. HINT: color argument takes a vector of same length of number of data points data points with the level info.

Exercise 4

To the same code in the previous exercise, use the size argument to specify the markers’ size based on the third column of the iris dataset.

Exercise 5

a. Generate a line plot for 100 values of random normal distribution with the default mean and standard deviation.
HINT: Use index values on x axis. Use type="scatter" and mode="lines" to get a line chart

Exercise 6

b. Save the previous plot in an object p. Use layout function to add an appropriate title to the plot.

Exercise 7

To learn how to generate a bar plot, we will simulate sample data and look at how to prepare the data before plotting.
Run the below code to generate the data.
cat <- c(rep("A", 2), rep("B", 4), rep("C", 8))

Data has to be in the form of Levels and their Counts . Therefore, using table() function to summarize and as.data.frame to create a data frame.
df <- as.data.frame(table(cat))

a. Now, using type="bar" and the appropriate x and y arguments, create a bar graph.
b. Add color to each bar using color argument, based on the categorical levels.

Exercise 8

Pie chart is an alternative way of representing categorical data, but, when the levels in the data are more, bar chart is preferred.
Data has to be prepared in the same way as we do it for bar chart. The arguments vary a little. Instead of x and y, we use labels and values.

Generate a pie chart using the same data from the previous exercise and appropriate arguments.

Notice how the tick marks and the axes appear behind the chart.

Exercise 9

For the first column in the iris dataset, generate a box plot using the box trace type.
HINT:For a simple box plot, just the y argument and type argumnets are given.

Exercise 10

Add another argument to the code used in the previous exercies to generate mutliple box plots for the first column of iris dataset, where each box corresponds to data of particular Species.
HINT : Remember the argument we used to specify the color for each species in Exercise 3.

In the coming exercise sets on plotly, we will work on some advanced plots and see how to use argumnets from the layout function to manipulate the plot layout and settings.




Descriptive Analytics-Part 6: Interactive dashboard ( 2/2)

downloadDescriptive Analytics is the examination of data or content, usually manually performed, to answer the question “What happened?”.As this series of exercises comes to an end, the last part is going to be the development of a data product. Not everybody is able to code in R, so it is useful to be able to make GUIs in order to share your work with non-technical people. This part may be a little challenging, since it requires some basic knowledge of the shiny package. The outcome of this set of exercises will be almost like this web app (some variables are missing because I had to reduce the size of the data set).

In order to be able to solve this set of exercises you should have solved the part 0, part 1, part 2,part 3, and part 4 of this series but also you should run this script which contain some more data cleaning. In case you haven’t, run this script in your machine which contains the lines of code we used to modify our data set. This is the tenth set of exercise of a series of exercises that aims to provide a descriptive analytics solution to the ‘2008’ data set from here. This data set which contains the arrival and departure information for all domestic flights in the US from 2008 has become the “iris” data set for Big Data. The goal of Descriptive analytics is to inform the user about what is going on at the dataset. Before proceeding, it might be helpful to look over the help pages for the fluidPage, pageWithSidebar, headerPanel , sidebarPanel, selectInput, mainPanel, tabPanel, observe, verbatimTextOutput, renderPrint, shinyApp.

For this set of exercises you will need to install and load the package shiny.

install.packages('shiny')
library(shiny)

I have also changed the values of the DaysOfWeek variable, if you wish to do that as well the code for that is :
install.packages('lubridate')
library(lubridate)
flights$DayOfWeek <- wday(as.Date(flights$Full1_Date,'%m/%d/%Y'), label=TRUE)

Because the app requires some time to run, I have also removed the rows with missing values from the data set just to save some time.

flights <-flights[which(!is.na(flights['WeatherDelay'])),]
flights <-flights[which(!is.na(flights['ArrDelay'])),]

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page. Moreover it would be really nice of you to share the links of the apps you have developed. It would be a great contribution the community.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Create the user interface and set as the header of the web app : “Descriptive Analysis”

Exercise 2

Create a side panel.

Exercise 3

Create two select list input control. The former will contain the variables: CarrierDelay, WeatherDelay, NASDelay, SecurityDelay, LateAircraftDelay. The latter will contain the variables :Dest, Origin, UniqueCarrier, TailNum, CancellationCode.

Exercise 4

Create a set of radio buttons used to select a plot from a list ( Histogram, Scatter plot, Violin plot),and set as default plot the Histogram.

Exercise 5

Create a set of radio buttons used to select a plot from a list ( bar plot, pie chart, rose wind),and set as default plot the bar plot.

Exercise 6

Create a main panel.

Exercise 7

Create in the main panel two tabs named “Delays” and “Categorical” that will contain the plots of the exercises 4 and 5 respectively.

Exercise 8

Now that we are done with the user interface, create the server side of the app. Create the output of the first tab, which will be the plots from exercise 4 in respect to the first set of variables from exercise 3 ( notice that they are all continuous variables), bear in mind that at the scatter plot the x-axis should be the Full_Date and at the violin plot the x-axis should be the DayOfWeek as we did at the previous set of exercises. (please check out the first tab of the app, to make things more clear).

Exercise 9

Create the output of the second tab, , which will be the plots from exercise 5 in respect to the second set of variables from exercise 3 from the exercise 5, use the knowledge you applied ( or acquired at the previous exercises for the plots, make them as interesting as you can).(please check out the second tab of the app, to make things more clear).

Exercise 10

Launch the app.




Descriptive Analytics-Part 6: Interactive dashboard ( 1/2)

downloadDescriptive Analytics is the examination of data or content, usually manually performed, to answer the question “What happened?”.As this series of exercises comes to an end, the last part is going to be the development of a data product. Not everybody is able to code in R, so it is useful to be able to make GUIs in order to share your work with non-technical people. This part may be a little challenging, since it requires some basic knowledge of the shiny package. The outcome of this set of exercises will be almost like this web app (some variables are missing because I had to reduce the size of the data set).

In order to be able to solve this set of exercises you should have solved the part 0, part 1, part 2,part 3, and part 4 of this series but also you should run this script which contain some more data cleaning. In case you haven’t, run this script in your machine which contains the lines of code we used to modify our data set. This is the ninth set of exercise of a series of exercises that aims to provide a descriptive analytics solution to the ‘2008’ data set from here. This data set which contains the arrival and departure information for all domestic flights in the US from 2008 has become the “iris” data set for Big Data. The goal of Descriptive analytics is to inform the user about what is going on at the dataset. Before proceeding, it might be helpful to look over the help pages for the fluidPage, pageWithSidebar, headerPanel , sidebarPanel, selectInput, mainPanel, tabPanel, verbatimTextOutput, renderPrint, shinyApp.

For this set of exercises you will need to install and load the package shiny.

install.packages('shiny')
library(shiny)

I have also changed the values of the DaysOfWeek variable, if you wish to do that as well the code for that is :
install.packages('lubridate')
library(lubridate)
flights$DayOfWeek <- wday(as.Date(flights$Full1_Date,'%m/%d/%Y'), label=TRUE)

Because the app requires some time to run, I have also removed the rows with missing values from the data set just to save some time.

flights <-flights[which(!is.na(flights['WeatherDelay'])),]
flights <-flights[which(!is.na(flights['ArrDelay'])),]

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Create the user interface and set as the header of the web app : “Descriptive Analysis”

Exercise 2

Create a side panel.

Exercise 3

Create a select list input control that contains the functions : summary, str, head, tail, names, summary.

Exercise 4

Create a select list input control that contains the functions : mean, median, max, min, range, sd.

Exercise 5

Create a select list input control that contains the variables : ActualElapsedTime, CRSElapsedTime, AirTime, ArrDelay, DepDelay, TaxiIn, TaxiOut.

Exercise 6

Create a main panel.

Exercise 7

Create in the main panel two tabs named “Content” and “Measures” that will contain the output of the functions of exercise 3 and exercise 4 respectively.

Exercise 8

Now that we are done with the user interface, create the server side of the app and the output that is supposed to print the functions of the exercise 3. (please check out the first tab of the app, to make things more clear).

Exercise 9

Create the output of the second tab, combining the functions of exercise 4 and the variables from the exercise 5.(please check out the second tab of the app, to make things more clear).

Exercise 10

Launch the app.




Working with Shapefiles in R Exercises

R has many powerful libraries to handle spatial data, and the things that R can do with maps can only grow. This exercise tries to demonstrate a few basic functionalities of R while dealing with shapefiles.

A shapefile is a simple, nontopological format for storing the geometric location and attribute information of geographic features. Geographic features in a shapefile can be represented by points, lines, or polygons (ESRI). The geographic features are associated with an attribute table which is very similar to an R dataframe.

The rgdal package in R provides bindings to the popular Geospatial Data Abstraction Library (GDAL) for reading, writing and converting between spatial formats. We are using a very popular dataset of London sports participation shapefile (download here). The attributes Pop_2001 and Partic_Per represents the population of London Boroughs in 2001 and the percentage of the population participating in sporting activities.

Answers to the exercises are available here. If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Please install and load the package rgdal before starting the exercises.

Exercise 1
Read the London Sports map from the shapefile london_sports.shp .

Exercise 2
Change the coordinate system of the map to WGS 84.

Exercise 3
Find the names of the zones where sports participation rates is more than 25%.

Exercise 4
Plot the london map in Sky Blue, along with a title.

Exercise 5
Plot the zones in London with Sports Participation Rates less than 15% in red. Retain the earlier blue color for other zones.

Exercise 6
Plot the zones in London with Sports Participation Rates more than 25% in green. Retain the earlier color for other zones.

Exercise 7
Place a black circle marker at the centre of each zone. Retain previous maps.

Exercise 8
Put labels for each zone. Place the labels to the right of the black marker.

Exercise 9
Add another categorical attribute sports_part which has values "low", "medium" and "high" for sports participation rates less than equal to 15%, between 15 to 25% and greater than 25% respectively.

Exercise 10
Save the new map object with modified attribute table as a new shapefile “london_sport2.shp”.




Building Shiny App exercises part 4

APPLICATION LAYOUT & REACTIVITY
The fourth part of our series is “separated” into two “sub-parts”. In the first one we will start building the skeleton of our application by using tabsetPanel. This is how we will separate the sections of our app and also organize its structure better.
In the second part you will learn hot to load your dataset in RStudio and finally in the third one we will give life to your Shiny App! Specifically, you are going to have your first contact with reactivity and learn how to build reactive output to display in your Shiny app in a form of a data table initially.
Follow the examples below to understand the logic of the tools you are going to use and then enhance the app you started creating in part 1 by practising with the exercise set we prepared for you. Lets begin!

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

TABSET PANEL
In the example below you will see hot to add a tabsetPanel in your shiny app.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs"))
))

#server.R
library(shiny)
shinyServer(function(input, output) {
})

Exercise 1

Add a tabsetPanel to the mainPanel of your Shiny App.

TAB PANEL
In the example below you will see how to add tabPanel in your tabsetPanel.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1")
))))

#server.R
library(shiny)
shinyServer(function(input, output) {
})

Exercise 2

Place a tabPanel in the tabsetPanel you just added to your Shiny App. Name it “Data Table”.

Exercise 3

Put a second tabPanel next to the first one. Name it “Summary”.

LOAD DATASET
Now it is time to give your app a purpose of existence. This can happen with only one way. To add some data into it! As we told in part 1 we will create an application based on the famous (Fisher’s or Anderson’s) iris data set which gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.
This is a “built in” dataset of RStudio that will help us create our first application.
But normally you want to analyze your own datasets. The first thing you should do in order to perform any kind of analysis on them is to load them properly. We will now see how to load a dataset in txt form from a local file using RStudio. Let’s go!
The process is quite simple. First of all you have to place the txt file that contains your dataset into the same directory that you are working, secondly press the “Import Dataset” button in RStudio and then “From Local File…”. Find the txt file in your computer and click “Open”, then press “Import”. That’s all! Your dataset is properly loaded in your directory and now you can work with it.
Please note that the purpose of this series is not to teach how to form your dataset before you load it nor how to “clean” it. You can gain more information about this subject from here. Our purpose is to teach you build your first Shiny App.

Exercise 4

Load the dataset you want to analyze (“something.txt”) from your computer to your directory with RStudio buttons.

INTRODUCTION TO REACTIVITY
From this point you are going to enter in the “Kingdom of Reactivity”. Reactive output automatically responds when your user interacts with a widget. You can create reactive output by following two steps. Firstly, add an R object to your ui.R. and then tell Shiny how to build the object in server.R.

1): Add an R object to the UI

Shiny provides a variety of functions that transform R objects into output for your UI as you can see below:

htmlOutput: raw HTML
imageOutput: image
plotOutput: plot
tableOutput: table
textOutput: text
uiOutput: raw HTML
verbatimTextOutput: text

To add output to the UI place the output function inside sidebarPanel or mainPanel in the ui.R script.
For example, the ui.R file below uses tableOutput to add a reactive line of text to “Tab Panel 1”. Nothing happens…for the moment!

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
})

Notice that datatableOutput takes an argument, the character string “dt1”. Each of the *Output functions require a character string that Shiny will use as the name of your reactive element. Users cannot see it and you will understand its role later.

Exercise 5

Add a datatableOutput to “Data Table”, name its argument “Table”.

2): Provide R code to build the object.

The code should be placed in the function that appears inside shinyServer in your server.R script.
This function is of great importance as it builds a list-like object named output that contains all of the code needed to update the R objects in your app. Be careful, each R object MUST have its own entry in the list.
You can create an entry by defining a new element for output within the function. The element name should match the name of the reactive element that you created in ui.R.
Each entry should contain the output of one of Shiny’s render* functions. Each render* function corresponds to a specific type of reactive object. You can find them below:

renderImage: images (saved as a link to a source file)
renderPlot: plots
renderPrint: any printed output
renderTable: data frame, matrix, other table like structures
renderText: character strings
renderUI: a Shiny tag object or HTML

Each render* function takes a single argument: an R expression which can either be one simple line of text, or it can involve many lines of code.
In the example below “dt1” is attached to the output expression in server.R and gives us the Data Table of “iris” dataset inside “Tab Panel 1”.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris)

})

Exercise 6

Add the appropriate render* function to server.R in order to create the Data table of the “iris” dataset. Hint: Use the output expression.

The dataTableOutput is your first contact with reactivity, in the next parts of our series you will use the rest of the Output functions that Shiny provides. But for now let’s experiment a little bit on this.
As you can see there is a text filter in your Data Table. You can deactivate it by setting searching to be “FALSE” as the example below.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris,options = list(searching=FALSE))
})

Exercise 7

Disable the Text Filter of your Data Table. Hint: Use options, list and searching.

With the same logic you can disable the pagination that is displayed in your Data Table, as in the example below.

# ui.R

library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris,options = list(searching=FALSE,paging=FALSE))
})

Exercise 8

Disable the Pagination of your Data Table. Hint: Use options, list, paging.
Now you can see how to display an exact number of rows (15) and enable filtering again.

# ui.R

library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris,options = list(pageLength=15))
})

Exercise 9

Enable filtering again and set the exact number of rows that are displayed to 10. Hint: Use options, list, pageLength

We can also create a Length Menu in order to control totally the choices of the numbers of rows we want to be displayed. In the example below we assign every number to a menu label. 5 -> ‘5’, 10 -> ’10’, 15 -> ’15’,-1 -> ‘ALL’.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris,options = list(
lengthMenu = list(c(5, 15, 25,-1),c('5','15','25','ALL')),
pageLength = 15))
})

Exercise 10

Create a Length Menu with values (10,20,30,-1) and assign each one ot the values to the appropriate menu label. Hint: Use options, list, lengthMenu,pageLength.




Building Shiny App exercises part 3

ADD CONTROL WIDGETS
Welcome to the third part of our series. In this part you will learn how to build and place inside your app the rest of the widgets which were mentioned in part 2.
More specifically we will analyze: 1) helptext, 2) numericInput, 3) radioButtons, 4) selectInput, 5) sliderInput and 6) textInput.
As you already know from part 2 reactivity will be added in the upcoming parts of our series so this is something that you do not have to worry about.
Follow the examples below to understand the logic behind the widgets’ functions and then enhance the app you created in part 1 by practising with the exercise set we prepared for you.
Firstly, we will add all the kinds of the widgets in our app, for educational reasons and later we will decide which of them is practical to keep.Let’s start!

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

To begin with let’s create the space inside our sidebarPanel in order to put in there the rest of our widgets.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Use the function fluidrow to make sure that all the elements we are going to use will be in the same line. To do this put fluidrow just under the “Menu” in your sidebarPanel and close its parenthesis just before the submibutton (excluding the two br).

HELP TEXT

In the example below we create a UI with a helpText.
# ui.R
shinyUI(fluidPage(
titlePanel("Widgets"),
h3("Help Text"),
helpText("Text that is used to provide some extra details to the user.")))

# server.R
shinyServer(function(input, output) {
})

Exercise 2

Place a helpText exactly under the actionButton, name it “Help Text” and as text add:”For help”. Hint: Use h4.

Exercise 3

Now use column function in order to decide the column width for every row and put the two widgets in the same line. To do this place the column function twice. Firstly place it just before the “Actionbutton” title with width = 6 and close its parenthesis exactly after the label “Perform”. Do the same for the helpInput. Both of the column functions must be inside the same fluidrow.

NUMERIC INPUT

In the example below we create a UI with a numericInput.
# ui.R
shinyUI(fluidPage(
titlePanel("Widgets"),
numericInput("num",
label = h3("Numeric Input"),
value = 1)
))

# server.R
shinyServer(function(input, output) {
})

Exercise 4

Put a numericInput under helpText,in the same row with submitButton. Name it “numer”, give it “Numeric Input” as label and value = 10. Hint: Use h4, fluidrow and column.

RADIO BUTTONS

In the example below we create a UI with a radioButtons.
#ui.R
shinyUI(fluidPage(
titlePanel("Widgets"),
radioButtons("radio", label = h3("Radio buttons"),
choices = list("Choice 1" = 1, "Choice 2" = 2,
"Choice 3" = 3),selected = 1)
))

#server.R
shinyServer(function(input, output) {
})

Exercise 5

Add radioButtons under numericInput, in the same row with checkBoxInput. Name it “radiobuttons”, put as label “Radio Buttons” and give it two choices with no default. Hint: Use h4, fluidrow, column and choices.

Exercise 6

Now put “2” as the default of the choices. Hint: Use selected.

SELECT INPUT

In the example below we create a UI with a selectInput.
# ui.R
shinyUI(fluidPage(
titlePanel("Widgets"),
selectInput("select", label = h3("Select Box"),
choices = list("Choice 1" = 1, "Choice 2" = 2,
"Choice 3" = 3), selected = 1)
))

#server.R
shinyServer(function(input, output) {
})

Exercise 7
Place under radiobuttons and in the same row with checkBoxGroupInput a selectinput. Its name should be “select”, its label “Select Box” and you should give it two choices with the second one as default. Hint: Use h4, fluidrow, column, choices and selected.

SLIDER INPUT

In the example below we create a UI with two sliderInput.
# ui.R
shinyUI(fluidPage(
titlePanel("Widgets"),
sliderInput("slider1", label = h3("Sliders"),
min = 0, max = 10, value = 5),
sliderInput("slider2", "",
min = 0, max = 10, value = c(3, 7))
))

#server.R
shinyServer(function(input, output) {
})

Exercise 8

Under the selectInput and in the same row with the dateInput place a sliderInput with name = slider1, label = “Sliders”, min = 0, max = 100 and value =50. Hint: Use fluidrow, columns and h4.

Exercise 9

Replace the value with a default range “10-90” and see the difference.

TEXT INPUT

In the example below we create a UI with a textInput.
# ui.R
shinyUI(fluidPage(
titlePanel("Widgets"),
textInput("text", label = h3("Text Input"),
value = "Text..."))
)

#server.R
shinyServer(function(input, output) {
})

Exercise 10

Finally put a textInput under sliderInput and in the same row with the dateRangeInput. Name it “text”, put as label “Text Input” and as value “Some Text”. Hint: Use fluidrow, column and h4.




Building Shiny App exercises part 2

ADD CONTROL WIDGETS
In the second part of our series you will see how to add control widgets in your Shiny app. Widget is a web element that your users can interact with. The widgets provided by Shiny are:

FUNCTIONS
actionButton: Action Button
checkboxGroupInput: A group of check boxes
checkboxInput: A single check box
dateInput: A calendar for date selection
dateRangeInput: A pair of calendars for selecting a date range
fileInput: A file upload control wizard
helpText: Help text that can be added to an input form
numericInput: A field to enter numbers
radioButtons: A set of radio buttons
selectInput: A box with choices to select from
sliderInput: A slider bar
submitButton: A submit button
textInput: A field to enter text

ADDING WIDGETS
You can add widgets to your web page in the same way that you added other types of HTML content in part 1.
To add a widget to your app, place a widget function in sidebarPanel or in mainPanel in your ui.R file.
The first two arguments for each widget are a name for the widget which will be a character string that the user will not see, but you can use it to change the widget’s value and a label which will appear with the widget in your app and it should be a character string too.
The rest of the arguments vary from widget to widget, depending on what the widget needs to be functional. They may be initial values, ranges, and increments.
Follow the examples below to understand the logic behind the widgets’ functions and then enhance the app you created in part 1 by practising with the exercise set we prepared for you.
Firstly, we will add all the kinds of the widgets to our app, for educational reasons and later we will decide which of them is practical to keep.
Note that we will just add the buttons in this part. Reactivity will be added to them in a few chapters. Lets begin!

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Open the app you created in part 1 and move the image from sidebarPanel to mainPanel, leave two rows under the title “Main”, put the image there and change its dimensions to: height = 150 and width = 200. HINT: Use br.

BUTTONS
In the example below we create a UI with a submitButton and an actionButton. Please note that we use the function fluidrow to make sure that all the elements we are going to use will be in the same line as we are going to need this in the next parts:
# ui.R
shinyUI(fluidPage(
titlePanel(“Widgets”),

fluidRow(h3(“Buttons”),
actionButton(“action”, label = “Action”),
br(),
br(),
submitButton(“Submit”))))

# server.R
shinyServer(function(input, output) {
})

Exercise 2

Leave a row and place an actionButton under the title “Menu” in sidebarPanel, give it the title “Actionbutton”, name = “per” and label = “Perform”. HINT: Use br and h4.

Exercise 3

Leave a row from the actionButton you just placed and add a submitButton with title = “Submitbutton” and name = “Submit”. HINT: Use br and h4.

SINGLE CHECKBOX
In the example below we create a UI with a single Checkbox:
# ui.R
shinyUI(fluidPage(
titlePanel(“Widgets”),

fluidRow(h3(“Single checkbox”),
checkboxInput(“checkbox”, label = “Choice A”, value = TRUE))))

#server.R
shinyServer(function(input, output) {
})

Exercise 4

Add a checkboxInput in the sidebarPanel under the submitButton, put as title “Single Checkbox”, name it “checbox”, name the label “Choice A” and set the value to “TRUE”. HINT: Use h4.

Exercise 5

Change the value to “FALSE” to understand the difference.

CHECKBOX GROUP
In the example below we create a UI with a Checkbox Group:
#ui.R
shinyUI(fluidPage(
checkboxGroupInput(“checkGroup”,
label = h3(“Checkbox group”),
choices = list(“Choice 1” = 1,
“Choice 2” = 2, “Choice 3” = 3),
selected = 2)
))

#server.R
shinyServer(function(input, output) {
})

Exercise 6

Place a checkboxGroupInput under the checkboxInput, give it title “Checkbox Group”, name it “checkGroup”, name the label “Checkbox Group” and give it 3 choices. HINT: Use h4

Exercise 7

Make the second of the choicesthe default one.

DATE INPUT
In the example below we create a UI with a Date Input:
#ui.R
shinyUI(fluidPage(
dateInput(“date”,
label = h3(“Date input”),
value = “2016-12-07”)
))

#server.R
shinyServer(function(input, output) {
})

Exercise 8

Under the checkboxGroupInput add a dateInput with name = “date”, label = “Date Input” and value = “2016-12-01”.

DATE RANGE
In the example below we create a UI with a Date Range Input:
#ui.R
shinyUI(fluidPage(
dateRangeInput(“dates”, label = h3(“Date range”))
))

#server.R
shinyServer(function(input, output) {
})

Exercise 9

Under the dateInput place a dateRangeInput with name = “dates” and label = “Date Range”. HINT: Use h4.

FILE INPUT
In the example below we create a UI with a File Input.
#ui.R
shinyUI(fluidPage(
fileInput(“file”, label = h3(“File input”))
))

#server.R
shinyServer(function(input, output) {
})

Exercise 10

Under the dateRangeInput place a fileInput. Name it “file” and give it the label “File Input”.




Building Shiny App exercises part 1

INTRODUCTION TO SHINY
Shiny is a package from RStudio that can be used to build interactive web pages with RStudio which is is an open source set of integrated tools designed to help you be more productive with R and you can download it from here. Use the examples in this tutorial to “take a first bite” and prepare for the exercises that follow and will help you build your first Shiny Application from “zero point”. This is the first part of the series and we will just create the interface, make some HTML formatting and add an image to our application. Specifically we will start creating a Shiny Application that will analyze the famous (Fisher’s or Anderson’s) iris data set which gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica. Lets go!
BUILDING INTERFACE (UI)
Every Shiny application includes two parts: a web page which shows the app to the user (UI), and a computer that activates the app (server). You need to create these two parts. UI is just a web document that the user gets to see and is responsible for creating the layout of the app and telling Shiny exactly where things go. The server is responsible for the logic of the app.
You can create a Shiny app by making a new directory and saving a ui.R and server.R file inside it. Each app will need its own unique directory.
You can run a Shiny app by giving the name of its directory to the function runApp(). For example if your Shiny app is in a directory called “Shiny App”, run it with the following code:

library(shiny)
runApp("Shiny App")

Or by just clicking the “Run App” button at the top of the editor which is the safest solution.

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Create a new directory named “Shiny App” in your working directory.

Exercise 2

Create the ui.r and server.r files.

Secondly, we have to install the “Shiny” package with:

install.packages("shiny")

and then we will call it with:

library(shiny)

Now that we analyzed the structure of a Shiny app, we will show you how to build a user-interface for this.
To get started, we open the server.R and ui.R files and edit them like this:
#ui.R
shinyUI(fluidPage())
#server.R
shinyServer(function(input, output) {})
The result is an empty app with a blank user-interface, just to begin with.

Exercise 3

Create an empty app with a blank user-interface.

LAYOUT
Shiny ui.R scripts use the function fluidPage() to create a display that automatically adjusts to the dimensions of your user’s browser window. You lay out your app by placing elements in the fluidPage() function.
For example, the ui.R script below creates a user-interface that has a title panel and then a sidebar layout, which includes a sidebar panel and a main panel. Note that these elements are placed within the fluidPage() function.
#ui.R

shinyUI(fluidPage(
titlePanel("title panel"),
sidebarLayout(
sidebarPanel( "sidebar panel"),
mainPanel("main panel"))))

The TitlePanel() and sidebarLayout() are the two most used elements to add to fluidPage(). They create a basic Shiny app with a sidebar.
The sidebarLayout() always takes two arguments: sidebarPanel function output and mainPanel function output.

Exercise 4

Create titlePanel(), name it “Shiny App” and sidebarLayout(). Do not forget to add sidebarPanel() and mainPanel() inside this.

HTML Content
You can add content to your Shiny app by placing it inside a *Panel function.
HEADERS
To create a header element: select a header function e.g. (h1) and give it the text you want to see in the header.
For example, you can create a first level header that says “Title” with h1("Title").
To place the element in your app:
Put h1("Title") as an argument to titlePanel(), sidebarPanel(), or mainPanel().
The text will appear in the corresponding panel of your web page. You can place multiple elements in the same panel if you separate them with a comma.
#ui.R

shinyUI(fluidPage(
titlePanel("My Shiny App"),
sidebarLayout(
sidebarPanel(),
mainPanel(
h1("First level title"),
h2("Second level title")))))

Exercise 5

Create an HTML element to add the title “Menu” in the sidebarPanel() and “Main” in mainPanel() with one of Shiny’s tag functions. HINT: Use h1,h2.

FORMATTED TEXT
Shiny offers many tag functions for formatting text.Take a look:
p: A paragraph of text
h1: A first level header
h2: A second level header
a: A hyper link
br: A line break (e.g. a blank line)
div: A division of text with a uniform style
span: An in-line division of text with a uniform style
pre: Text ‘as is’ in a fixed width font
code: A formatted block of code
img: An image
strong: Bold text
em: Italicized text

Exercise 6

Add a paragraph in your mainPanel() with a description about the app you are going to make.”This famous (Fisher’s or Anderson’s) iris data set gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.” Use an HTML tag format. HINT:Use p.

Exercise 7

Link the word “iris” in the mainPanel() with this hyperlink “http://stat.ethz.ch/R-manual/R-devel/library/datasets/html/iris.html”. HINT: Use a.

Exercise 8

Add the title “Analysis” under the desciption paragraph of your mainPanel. Do not forget the comma separation. HINT: Use br and h2.

Exercise 9

Use bold text to the words “Iris setosa”,”versicolor” and “virginica”. HINT: Use strong.

IMAGES
Images can improve the appearance of your app and help users understand the content. Shiny uses img() function to put image files in your app. To insert an image, give the img() function the name of your image file as the src argument (e.g., img(src = "my_image.png")). You can also include other HTML parameters such as height and width. For example:

img(src = "my_image.png", height = 68, width = 68)
.
The img() function looks for your image file in a specific place. Your file must be in a folder named “www” in the same directory as the ui.R script. Shiny will share any file placed here with your user’s web browser, which makes “www” a great place to put images, style sheets, and other things the browser will need to build the web components of your Shiny app. So if you want to use an image named “something.png”, your Shiny App directory should look like this one:
#ui.R

shinyUI(fluidPage(
titlePanel("My Shiny App"),
sidebarLayout(
sidebarPanel(),
mainPanel(
img(src="something.png", height = 350, width = 350)))))

Exercise 10

Download this image and place it in a folder labeled “www” within your “Shiny App” directory. Name it “petal”, add .jpg extension and then call the img function inside the sidebarPanel(). Use height and width to decide its dimensions.




Descriptive Analytics-Part 5: Data Visualisation (Categorical variables)

downloadDescriptive Analytics is the examination of data or content, usually manually performed, to answer the question “What happened?”.

In order to be able to solve this set of exercises you should have solved the part 0, part 1, part 2,part 3, and part 4 of this series but also you should run this script which contain some more data cleaning. In case you haven’t, run this script in your machine which contains the lines of code we used to modify our data set. This is the sixth set of exercise of a series of exercises that aims to provide a descriptive analytics solution to the ‘2008’ data set from here. This data set which contains the arrival and departure information for all domestic flights in the US from 2008 has become the “iris” data set for Big Data. The goal of Descriptive analytics is to inform the user about what is going on at the dataset. A great way to do that fast and effectively is by performing data visualisation. Data visualisation is also a form of art, it has to be simple, comprehended and full of information. On this set of exercises we will explore different ways of visualising categorical variables using the famous ggplot2 package. Before proceeding, it might be helpful to look over the help pages for the ggplot, geom_bar, facet_wrap,facet_grid, coord_polar, geom_raster, scale_fill_distiller.

For this set of exercises you will need to install and load the packages ggplot2, code>dplyr, and RColorBrewer.

install.packages('ggplot2')
library(ggplot2)
install.packages('dplyr')
library(dplyr)
install.packages('RColorBrewer')
library(RColorBrewer)

I have also changed the values of the DaysOfWeek variable, if you wish to do that as well the code for that is :
install.packages('lubridate')
library(lubridate)
flights$DayOfWeek <- wday(as.Date(flights$Full1_Date,'%m/%d/%Y'), label=TRUE)

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Exercise 1
Construct a barplot which illustrates the number of flights per carrier.

Exercise 2
Make a barplot which illustrates the number of flights per carrier and each bar also contains information regarding the number of cancellations per carrier.

Exercise 3
Make a barplot which illustrates the number of flights per carrier but also for every carrier to have two bars that show the number of flights that were cancelled and the ones that departed.

Exercise 4
Make a barplot that shows the proportion of cancelled flights per carrier.

Exercise 5
Make seven barplots which illustrate the number of flights per carrier and each bar also contains information regarding the number of cancellations per carrier for every day of the week. hint:facet

Exercise 6
Make one barplot which illustrates the number of flights per carrier and each bar also contains information regarding the number of cancellations per carrier for every day of the week.

Exercise 7
Create a pie chart that illustrates the number of flights per carrier

Exercise 8
Create a wind rose that illustrates the number of flights per carrier for every day of the week.

Exercise 9
Make a heat map that illustrates the number of flights per carrier for every day of the week.

Exercise 10
With the same data from the heatmap from the previous exercise, also provide some information regarding the cancellation ratio (2 digits recommended) and make customise the heatmap in order for the higher values to be more distinctive.