Agenda


  • build
    • simple bar plot
    • stacked bar plot
    • grouped bar plot
    • proportional bar plot
  • map aesthetics to variables
  • specify values for
    • bar color
    • bar line color
    • bar line type
    • bar line size

Intro


  • a bar plot represents data in rectangular bars
  • the length of the bars are proportional to the values they represent
  • bar plots can be either horizontal or vertical
  • the X axis of the plot represents the levels or the categories
  • and the Y axis represents the frequency/count of the variable

Libraries


library(ggplot2)
library(readr)

Data


ecom <- read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/ecom.csv',
  col_types = list(col_factor(levels = c('Desktop', 'Mobile', 'Tablet')), 
  col_factor(levels = c(TRUE, FALSE)), col_factor(levels = c(TRUE, FALSE)), 
  col_factor(levels = c('Affiliates', 'Direct', 'Display', 'Organic', 'Paid', 'Referral', 'Social'))))
## # A tibble: 5,000 x 4
##     device bouncers purchase   referrer
##     <fctr>   <fctr>   <fctr>     <fctr>
##  1 Desktop    FALSE    FALSE Affiliates
##  2  Mobile    FALSE    FALSE Affiliates
##  3 Desktop     TRUE    FALSE    Organic
##  4 Desktop    FALSE    FALSE    Organic
##  5  Mobile     TRUE    FALSE     Direct
##  6 Desktop     TRUE    FALSE     Direct
##  7 Desktop    FALSE    FALSE   Referral
##  8  Tablet     TRUE    FALSE    Organic
##  9  Mobile     TRUE    FALSE     Social
## 10 Desktop     TRUE    FALSE    Organic
## # ... with 4,990 more rows

Data Dictionary


Below is the description of the data set:

  • device: device used to visit the website
  • bouncers: whether visit was a bouncer (exit website from landing page)
  • purchase: whether visitor purchased
  • referrer: referrer website/search engine

Aesthetics


  • fill
  • color
  • linetype
  • size
  • position

Simple Bar Plot


ggplot(ecom) +
  geom_bar(aes(factor(device)))

Bar Color


ggplot(ecom) +
  geom_bar(aes(factor(device)),
           fill = c('red', 'blue', 'green'))

Stacked Bar Plot


ggplot(ecom) +
  geom_bar(aes(device, fill = factor(referrer)))

Grouped Bar Plot


ggplot(ecom) +
  geom_bar(aes(device, fill = factor(referrer)), position = 'dodge')

Proportional Bar Plot


ggplot(ecom) +
  geom_bar(aes(device, fill = factor(referrer)), position = 'fill')

Horizontal Bar Plot


ggplot(ecom) +
  geom_bar(aes(factor(device), fill = factor(referrer))) +
  coord_flip()

Bar Line Color


ggplot(ecom) +
  geom_bar(aes(factor(device)), fill = 'white',
           color = c('red', 'blue', 'green'))

Bar Line Type


ggplot(ecom) +
  geom_bar(aes(factor(device)), fill = 'white', 
          color = 'black', linetype = 2)

Bar Line Size


ggplot(ecom) +
  geom_bar(aes(factor(device)), fill = 'white', 
           color = 'black', size = 2)