library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)

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:

inc <- inc[complete.cases(inc),]
# top 5 industries with a maximum employees. 
knitr::kable(group_by(inc, Industry) %>% summarize(Count=n()) %>% arrange(desc(Count)) %>% top_n(5))
## Selecting by Count
Industry Count
IT Services 732
Business Products & Services 480
Advertising & Marketing 471
Health 354
Software 341
# top 5 Cities with a maximum employees. 
knitr::kable(group_by(inc, City) %>% summarize(Count=n()) %>% arrange(desc(Count)) %>% top_n(5))
## Selecting by Count
City Count
New York 160
Chicago 90
Austin 88
Houston 76
San Francisco 74

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.

# Get a list of counts by state
stateCount <- group_by(inc, State) %>%
  summarize(Count=n()) 

# Plot results


ggplot(data = stateCount,
       aes(x = reorder(State, Count), y = Count))+
  geom_bar(stat = "identity")+
  coord_flip() +
  ggtitle("Distribution of 5,000 Fastest Growing Companies") + 
  labs( x = "State", y = "No of Companies")  +
  theme_gray(base_size = 6)

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.

# Get NY industry employees data
nydata <- filter(inc, State=="NY")

# plot the boxplot to identify the range and the presence of outliers.
ggplot(aes(x=Industry, y=Employees), data = nydata) + 
  stat_boxplot(geom ='errorbar') +
  geom_boxplot() + 
  ggtitle("NY - Employee Count per Industry*") + labs(x = "", y = "") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.3),
        axis.ticks.x = element_blank())

Above box plots are so much shrinked and there is a presence of outliers. We can remove the outliers by filtering the data which lies below the lower fence(Q1-1.5 IQR) and above the upper fence(Q3 + 1.5 IQR)

# clean the outliers

temp <- nydata %>% 
  group_by(Industry) %>% 
  mutate(iqr=IQR(Employees),q3=quantile(Employees)["75%"],q1=quantile(Employees)["25%"]) %>% 
  mutate(upper_lim=q3+1.5*iqr,lower_lim=q1-1.5*iqr)

noOutlier_nydata<- temp[which(temp$Employees<=temp$upper_lim & temp$Employees>=temp$lower_lim),]

Below is the boxplot after removing all the outliers

#plot the box plot with all outlier removed 
ggplot(aes(x=Industry, y=Employees), data = noOutlier_nydata) + 
  stat_boxplot(geom ='errorbar') +
  geom_boxplot() + 
  ggtitle("NY  - Employee Count per Industry") + labs(x = "", y = "") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.3),
        axis.ticks.x = element_blank())

# get the avg 
avgSummary_NY <- noOutlier_nydata %>% 
  group_by(Industry) %>% 
  summarise(avg=mean(Employees))
  # distribution of average employment for that State
ggplot(avgSummary_NY,aes(x=reorder(Industry, avg),y=avg))+
  geom_bar(stat = "identity")+
  coord_flip()+
  theme_classic()+
  labs(title="Employees", x="Industry",y="Average employees")

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.

# Get a list of counts by state
byIndustry <- group_by(inc, Industry) %>%
  summarize(total_rev= sum(Revenue),noofEmp=sum(Employees)) %>% mutate(avg_rev_emp=total_rev/noofEmp)

knitr::kable(byIndustry)
Industry total_rev noofEmp avg_rev_emp
Advertising & Marketing 7785000000 39731 195942.71
Business Products & Services 26345900000 117357 224493.64
Computer Hardware 11885700000 9714 1223563.93
Construction 13174300000 29099 452740.64
Consumer Products & Services 14956400000 45464 328972.37
Education 1139300000 7685 148249.84
Energy 13771600000 26437 520921.44
Engineering 2532500000 20435 123929.53
Environmental Services 2638800000 10155 259852.29
Financial Services 13150900000 47693 275740.67
Food & Beverage 12812500000 65911 194390.92
Government Services 6009100000 26185 229486.35
Health 17860100000 82430 216669.90
Human Resources 9246100000 226980 40735.31
Insurance 2337900000 7339 318558.39
IT Services 20525000000 102788 199682.84
Logistics & Transportation 14837800000 39994 371000.65
Manufacturing 12603600000 43942 286823.54
Media 1742400000 9532 182794.80
Real Estate 2956800000 18893 156502.41
Retail 10257400000 37068 276718.46
Security 3812800000 41059 92861.49
Software 8134600000 51262 158686.75
Telecommunications 7287900000 30842 236297.91
Travel & Hospitality 2931600000 23035 127267.20
ggplot(byIndustry,aes(x=byIndustry$Industry,y=avg_rev_emp))+
  geom_bar(stat = "identity")+
  coord_flip()+
  theme_classic()+
  labs(title="Revenue/Employee", x="Industry",y="Average revenue per employee")