Principles of Data Visualization and Introduction to ggplot2

I have provided you with data about the 5,000 fastest growing companies in the US, as compiled by Inc. magazine. lets read this in:

inc <- read.csv("https://raw.githubusercontent.com/charleyferrari/CUNY_DATA_608/master/module1/Data/inc5000_data.csv", header= TRUE)

And lets preview this data:

head(inc)
##   Rank                         Name Growth_Rate   Revenue
## 1    1                         Fuhu      421.48 1.179e+08
## 2    2        FederalConference.com      248.31 4.960e+07
## 3    3                The HCI Group      245.45 2.550e+07
## 4    4                      Bridger      233.08 1.900e+09
## 5    5                       DataXu      213.37 8.700e+07
## 6    6 MileStone Community Builders      179.38 4.570e+07
##                       Industry Employees         City State
## 1 Consumer Products & Services       104   El Segundo    CA
## 2          Government Services        51     Dumfries    VA
## 3                       Health       132 Jacksonville    FL
## 4                       Energy        50      Addison    TX
## 5      Advertising & Marketing       220       Boston    MA
## 6                  Real Estate        63       Austin    TX
summary(inc)
##       Rank                          Name       Growth_Rate     
##  Min.   :   1   (Add)ventures         :   1   Min.   :  0.340  
##  1st Qu.:1252   @Properties           :   1   1st Qu.:  0.770  
##  Median :2502   1-Stop Translation USA:   1   Median :  1.420  
##  Mean   :2502   110 Consulting        :   1   Mean   :  4.612  
##  3rd Qu.:3751   11thStreetCoffee.com  :   1   3rd Qu.:  3.290  
##  Max.   :5000   123 Exteriors         :   1   Max.   :421.480  
##                 (Other)               :4995                    
##     Revenue                                  Industry      Employees      
##  Min.   :2.000e+06   IT Services                 : 733   Min.   :    1.0  
##  1st Qu.:5.100e+06   Business Products & Services: 482   1st Qu.:   25.0  
##  Median :1.090e+07   Advertising & Marketing     : 471   Median :   53.0  
##  Mean   :4.822e+07   Health                      : 355   Mean   :  232.7  
##  3rd Qu.:2.860e+07   Software                    : 342   3rd Qu.:  132.0  
##  Max.   :1.010e+10   Financial Services          : 260   Max.   :66803.0  
##                      (Other)                     :2358   NA's   :12       
##             City          State     
##  New York     : 160   CA     : 701  
##  Chicago      :  90   TX     : 387  
##  Austin       :  88   NY     : 311  
##  Houston      :  76   VA     : 283  
##  San Francisco:  75   FL     : 282  
##  Atlanta      :  74   IL     : 273  
##  (Other)      :4438   (Other):2764

Think a bit on what these summaries mean. Use the space below to add some more relevant non-visual exploratory information you think helps you understand this data:

# Insert your code here, create more chunks as necessary
if(!(c("psych") %in% rownames(installed.packages()))) {install.packages('psych')}
library(psych)

if(!(c("pastecs") %in% rownames(installed.packages()))) {install.packages('pastecs')}
library(pastecs)
## Loading required package: boot
## 
## Attaching package: 'boot'
## The following object is masked from 'package:psych':
## 
##     logit
stat.desc(inc) 
##                      Rank Name  Growth_Rate      Revenue Industry
## nbr.val      5.001000e+03   NA 5.001000e+03 5.001000e+03       NA
## nbr.null     0.000000e+00   NA 0.000000e+00 0.000000e+00       NA
## nbr.na       0.000000e+00   NA 0.000000e+00 0.000000e+00       NA
## min          1.000000e+00   NA 3.400000e-01 2.000000e+06       NA
## max          5.000000e+03   NA 4.214800e+02 1.010000e+10       NA
## range        4.999000e+03   NA 4.211400e+02 1.009800e+10       NA
## sum          1.251071e+07   NA 2.306374e+04 2.411609e+11       NA
## median       2.502000e+03   NA 1.420000e+00 1.090000e+07       NA
## mean         2.501641e+03   NA 4.611826e+00 4.822254e+07       NA
## SE.mean      2.041222e+01   NA 1.997192e-01 3.401441e+06       NA
## CI.mean.0.95 4.001690e+01   NA 3.915372e-01 6.668317e+06       NA
## var          2.083710e+06   NA 1.994787e+02 5.786059e+16       NA
## std.dev      1.443506e+03   NA 1.412369e+01 2.405423e+08       NA
## coef.var     5.770237e-01   NA 3.062495e+00 4.988172e+00       NA
##                 Employees City State
## nbr.val      4.989000e+03   NA    NA
## nbr.null     0.000000e+00   NA    NA
## nbr.na       1.200000e+01   NA    NA
## min          1.000000e+00   NA    NA
## max          6.680300e+04   NA    NA
## range        6.680200e+04   NA    NA
## sum          1.161030e+06   NA    NA
## median       5.300000e+01   NA    NA
## mean         2.327180e+02   NA    NA
## SE.mean      1.915720e+01   NA    NA
## CI.mean.0.95 3.755654e+01   NA    NA
## var          1.830955e+06   NA    NA
## std.dev      1.353128e+03   NA    NA
## coef.var     5.814454e+00   NA    NA
describe(inc)
##             vars    n        mean           sd    median     trimmed
## Rank           1 5001     2501.64      1443.51 2.502e+03     2501.73
## Name*          2 5001     2501.00      1443.81 2.501e+03     2501.00
## Growth_Rate    3 5001        4.61        14.12 1.420e+00        2.14
## Revenue        4 5001 48222535.49 240542281.14 1.090e+07 17334966.26
## Industry*      5 5001       12.10         7.33 1.300e+01       12.05
## Employees      6 4989      232.72      1353.13 5.300e+01       81.78
## City*          7 5001      732.00       441.12 7.610e+02      731.74
## State*         8 5001       24.80        15.64 2.300e+01       24.44
##                     mad     min        max      range  skew kurtosis
## Rank            1853.25 1.0e+00 5.0000e+03 4.9990e+03  0.00    -1.20
## Name*           1853.25 1.0e+00 5.0010e+03 5.0000e+03  0.00    -1.20
## Growth_Rate        1.22 3.4e-01 4.2148e+02 4.2114e+02 12.55   242.34
## Revenue     10674720.00 2.0e+06 1.0100e+10 1.0098e+10 22.17   722.66
## Industry*          8.90 1.0e+00 2.5000e+01 2.4000e+01 -0.10    -1.18
## Employees         53.37 1.0e+00 6.6803e+04 6.6802e+04 29.81  1268.67
## City*            604.90 1.0e+00 1.5190e+03 1.5180e+03 -0.04    -1.26
## State*            19.27 1.0e+00 5.2000e+01 5.1000e+01  0.12    -1.46
##                     se
## Rank             20.41
## Name*            20.42
## Growth_Rate       0.20
## Revenue     3401441.44
## Industry*         0.10
## Employees        19.16
## City*             6.24
## State*            0.22
tail(inc)
##      Rank               Name Growth_Rate  Revenue
## 4996 4996              cSubs        0.34 1.34e+07
## 4997 4997          Dot Foods        0.34 4.50e+09
## 4998 4998 Lethal Performance        0.34 6.80e+06
## 4999 4999   ArcaTech Systems        0.34 3.26e+07
## 5000 5000                INE        0.34 6.80e+06
## 5001 5000               ALL4        0.34 4.70e+06
##                          Industry Employees         City State
## 4996 Business Products & Services        19     Montvale    NJ
## 4997              Food & Beverage      3919 Mt. Sterling    IL
## 4998                       Retail         8   Wellington    FL
## 4999           Financial Services        63       Mebane    NC
## 5000                  IT Services        35     Bellevue    WA
## 5001       Environmental Services        34    Kimberton    PA
table(inc$Industry)
## 
##      Advertising & Marketing Business Products & Services 
##                          471                          482 
##            Computer Hardware                 Construction 
##                           44                          187 
## Consumer Products & Services                    Education 
##                          203                           83 
##                       Energy                  Engineering 
##                          109                           74 
##       Environmental Services           Financial Services 
##                           51                          260 
##              Food & Beverage          Government Services 
##                          131                          202 
##                       Health              Human Resources 
##                          355                          196 
##                    Insurance                  IT Services 
##                           50                          733 
##   Logistics & Transportation                Manufacturing 
##                          155                          256 
##                        Media                  Real Estate 
##                           54                           96 
##                       Retail                     Security 
##                          203                           73 
##                     Software           Telecommunications 
##                          342                          129 
##         Travel & Hospitality 
##                           62

Question 1

Create a graph that shows the distribution of companies in the dataset by State (ie how many are in each state). There are a lot of States, so consider which axis you should use. This visualization is ultimately going to be consumed on a ‘portrait’ oriented screen (ie taller than wide), which should further guide your layout choices.

# Answer Question 1 here
if(!(c("ggplot2") %in% rownames(installed.packages()))) {install.packages('ggplot2')}
library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
ggp<-ggplot(data=inc, aes(x=State)) 
# counts
ggp + geom_histogram(fill="black",stat = "count") + coord_flip()+
theme_classic()+
    labs(title="Distribution of Companies", x="State",y="Number of Companies")
## Warning: Ignoring unknown parameters: binwidth, bins, pad

Quesiton 2

Lets dig in on the state with the 3rd most companies in the data set. Imagine you work for the state and are interested in how many people are employed by companies in different industries. Create a plot that shows the average and/or median employment by industry for companies in this state (only use cases with full data, use R’s complete.cases() function.) In addition to this, your graph should show how variable the ranges are, and you should deal with outliers.

Let’s rank the states by the number of companies they have, and find the 3rd state with most employees

if(!(c("dplyr") %in% rownames(installed.packages()))) {install.packages('dplyr')}
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:pastecs':
## 
##     first, last
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
df <- group_by(inc, State)
df <-summarise(df,count = n())
df <- arrange(df, desc(count))

#state with 3rd most companies is NY
df$State[3]
## [1] NY
## 52 Levels: AK AL AR AZ CA CO CT DC DE FL GA HI IA ID IL IN KS KY LA ... WY

We can see that the state with 3rd most companies is NY

Let’s filter the data for only NY state records and return only the records with no missing values

NY_inc <- filter(inc, State == df$State[3])
summary(NY_inc)
##       Rank                        Name      Growth_Rate    
##  Min.   :  26   1st Equity          :  1   Min.   : 0.350  
##  1st Qu.:1186   33Across            :  1   1st Qu.: 0.670  
##  Median :2702   5Linx Enterprises   :  1   Median : 1.310  
##  Mean   :2612   Access Display Group:  1   Mean   : 4.371  
##  3rd Qu.:4005   Adafruit            :  1   3rd Qu.: 3.580  
##  Max.   :4981   AdCorp Media Group  :  1   Max.   :84.430  
##                 (Other)             :305                   
##     Revenue                                  Industry     Employees      
##  Min.   :2.000e+06   Advertising & Marketing     : 57   Min.   :    1.0  
##  1st Qu.:4.300e+06   IT Services                 : 43   1st Qu.:   21.0  
##  Median :8.800e+06   Business Products & Services: 26   Median :   45.0  
##  Mean   :5.872e+07   Consumer Products & Services: 17   Mean   :  271.3  
##  3rd Qu.:2.570e+07   Telecommunications          : 17   3rd Qu.:  105.5  
##  Max.   :4.600e+09   Education                   : 14   Max.   :32000.0  
##                      (Other)                     :137                    
##         City         State    
##  New York :160   NY     :311  
##  Brooklyn : 15   AK     :  0  
##  Rochester:  9   AL     :  0  
##  Buffalo  :  5   AR     :  0  
##  Fairport :  5   AZ     :  0  
##  new york :  5   CA     :  0  
##  (Other)  :112   (Other):  0
NY_inc <- NY_inc[complete.cases(NY_inc),]

Let’s summarize the data and identify outliers outliers are those observations that lie outside 1.5*IQR, where IQR, the ‘Inter Quartile Range’ is the difference between 75th and 25th quartiles

# aggregate employees by Industry
Employment_by_Industry<- group_by(NY_inc,Industry) %>% 
  summarise(Avg_employee_cnt = mean(Employees), Median_Employee_cnt = median(Employees), Total_employee_cnt = sum(Employees) 
            , Min_employee_cnt = min (Employees), Max_employee_cnt = max(Employees) , 
    high_Outlier_limit = quantile (Employees)[4] + 1.5*IQR(Employees), low_Outlier_limit = quantile (Employees)[2] - 1.5*IQR(Employees)
            ,First_quartile = quantile(Employees)[2],
            First_quartile = quantile(Employees)[2] , third_quartile = quantile (Employees)[4])
Employment_by_Industry
## # A tibble: 25 x 10
##    Industry           Avg_employee_cnt Median_Employee_c~ Total_employee_~
##    <fct>                         <dbl>              <dbl>            <int>
##  1 Advertising & Mar~             58.4               38.0             3331
##  2 Business Products~           1492                 70.5            38804
##  3 Computer Hardware              44.0               44.0               44
##  4 Construction                   61.0               24.5              366
##  5 Consumer Products~            626                 25.0            10647
##  6 Education                      59.9               50.5              838
##  7 Energy                        129                120                646
##  8 Engineering                    53.5               54.5              214
##  9 Environmental Ser~            155                155                310
## 10 Financial Services            144                 81.0             1876
## # ... with 15 more rows, and 6 more variables: Min_employee_cnt <dbl>,
## #   Max_employee_cnt <dbl>, high_Outlier_limit <dbl>,
## #   low_Outlier_limit <dbl>, First_quartile <dbl>, third_quartile <dbl>

Let’s create a plot that shows the average and median employment by industry for companies in NY state, without dealing with outliers and showing variability using boxplots. Points outside the whiskers of the boxplot are outliers

g <- ggplot(NY_inc, aes(x = Industry, y = Employees)) +
        geom_boxplot()
  g+ coord_flip() 

Let’s remove the outliers and reproduce the boxplot

g <- ggplot(NY_inc, aes(x = Industry, y = Employees)) +
        geom_boxplot(outlier.shape = NA)
  g + coord_flip() +
  scale_y_continuous(limits = quantile(NY_inc$Employees, c(0.1, 0.9)))
## Warning: Removed 62 rows containing non-finite values (stat_boxplot).

Question 3

Now imagine you work for an investor and want to see which industries generate the most revenue per employee. Create a chart that makes this information clear. Once again, the distribution per industry should be shown.

Let’s get only the cases without missing values

# Answer Question 3 here
INC_2 <- inc[complete.cases(inc),]

INC_summary <- group_by(INC_2,Industry) %>% 
  summarise( Total_employee_cnt = sum(Employees) 
            , Total_Revenue = sum (Revenue), Revenue_per_employee = sum (Revenue)/sum(Employees))

INC_summary2 <-arrange(INC_summary, desc(Revenue_per_employee))
INC_summary2
## # A tibble: 25 x 4
##    Industry             Total_employee_c~ Total_Revenue Revenue_per_emplo~
##    <fct>                            <int>         <dbl>              <dbl>
##  1 Computer Hardware                 9714   11885700000            1223564
##  2 Energy                           26437   13771600000             520921
##  3 Construction                     29099   13174300000             452741
##  4 Logistics & Transpo~             39994   14837800000             371001
##  5 Consumer Products &~             45464   14956400000             328972
##  6 Insurance                         7339    2337900000             318558
##  7 Manufacturing                    43942   12603600000             286824
##  8 Retail                           37068   10257400000             276718
##  9 Financial Services               47693   13150900000             275741
## 10 Environmental Servi~             10155    2638800000             259852
## # ... with 15 more rows
ggp<- ggplot(data=INC_summary2, aes(x=Industry, y=Revenue_per_employee)) 
# counts
ggp + geom_bar(fill="black",stat = "identity") + coord_flip()