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:

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
# list types for each attribute
sapply(inc, class)
##        Rank        Name Growth_Rate     Revenue    Industry   Employees 
##   "integer"    "factor"   "numeric"   "numeric"    "factor"   "integer" 
##        City       State 
##    "factor"    "factor"
# Insert your code here, create more chunks as necessary
sd(inc$Growth_Rate)
## [1] 14.12369
sd(inc$Revenue)
## [1] 240542281
sd(inc$Employees, na.rm = TRUE)#A few companies have missing employee counts
## [1] 1353.128
#We can also do IQR in case the data is skewed
IQR(inc$Growth_Rate)
## [1] 2.52
IQR(inc$Revenue)
## [1] 23500000
IQR(inc$Employees, na.rm = TRUE)
## [1] 107
#Revenue has quite a large range. I used a base 10 logrithm to compress that scale.
#I used mutate from tidyr to make these new calculations part of the dataframe for later use.
inc <- inc %>% mutate(log_Rev = log10(Revenue))
inc$log_Rev %>% summary()
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   6.301   6.708   7.037   7.132   7.456  10.004
# I also like doing ratios, in this case normalizing businesses of different sizes to see how much revenue or growth is generated per employee. 
inc <- inc %>% 
  mutate(rev_per_empl = Revenue/Employees)
inc$rev_per_empl %>% 
  summary() 
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.     NA's 
##     1801   125000   198658   393613   375000 40740000       12
inc <- inc %>% 
  mutate(grw_per_empl = Growth_Rate/Employees)
inc$grw_per_empl %>% 
  summary()
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.      NA's 
##  0.000015  0.009022  0.027857  0.168649  0.093446 13.342500        12
inc <- inc %>% 
  mutate(log_rev_per_grw = log10(Revenue/Growth_Rate))
inc$log_rev_per_grw %>% 
  summary()
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   5.015   6.376   6.873   6.876   7.366  10.392
#  growth rate by industry
gr_industry<-inc %>% 
  select (Industry,Growth_Rate) %>% 
  group_by(Industry) %>% 
  summarise(avg_gr= mean(Growth_Rate)) %>% 
  arrange(desc(avg_gr))
head(gr_industry)
## # A tibble: 6 x 2
##   Industry                     avg_gr
##   <fct>                         <dbl>
## 1 Energy                         9.60
## 2 Consumer Products & Services   8.78
## 3 Real Estate                    7.75
## 4 Government Services            7.24
## 5 Advertising & Marketing        6.23
## 6 Retail                         6.18
#  growth rate by city

gr_city<-inc %>% 
  select (City,Growth_Rate) %>% 
  group_by(City) %>% 
  summarise(avg_gr= mean(Growth_Rate)) %>% 
  arrange(desc(avg_gr))
head(gr_city)
## # A tibble: 6 x 2
##   City       avg_gr
##   <fct>       <dbl>
## 1 Dumfries    248. 
## 2 Chino       111. 
## 3 columbus    100. 
## 4 Cupertino    92.4
## 5 Bluffdale    59.9
## 6 El Segundo   56.2

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.

library(ggplot2)
q1_data<-inc %>% 
  select (Name,State) %>% 
  group_by(State) %>% 
  dplyr::summarise(company_count = n_distinct(Name)) %>% 
  arrange(desc(company_count))

q1<-ggplot(q1_data, aes(x=reorder(State,company_count), y=company_count)) +
  geom_bar(stat="identity")+
  geom_col(aes(fill = company_count)) + 
  geom_point(size=0.5, colour = "red") +
  scale_fill_gradient2(low = "white", high = "red") + 
  theme_bw()+
  coord_flip() + 
  theme(text = element_text(size = 9, color = "black")) +
  ggtitle ("Number Of Fastest Growing Companies By State") + ylab("Number of Companies") +
  theme(axis.title.y=element_blank()) + 
  theme(legend.position="none")

q1

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.

# Answer Question 2 here
ny_data <- inc  %>% 
  filter(State == 'NY', complete.cases(.)) %>% 
  arrange(Industry) %>% select(Industry, Employees) 
ny_data <- ny_data %>% group_by(Industry) %>% 
  filter(!(abs(Employees - median(Employees)) > 1.5*IQR(Employees)))# Using 1.5xIQR as the outlier limit
ny_data
## # A tibble: 262 x 2
## # Groups:   Industry [25]
##    Industry                Employees
##    <fct>                       <int>
##  1 Advertising & Marketing        79
##  2 Advertising & Marketing        27
##  3 Advertising & Marketing        89
##  4 Advertising & Marketing        75
##  5 Advertising & Marketing        42
##  6 Advertising & Marketing        15
##  7 Advertising & Marketing        46
##  8 Advertising & Marketing        19
##  9 Advertising & Marketing        45
## 10 Advertising & Marketing        12
## # … with 252 more rows
#The 1.5xIQR rule reduced the number of negative error bars better than the 2xstd dev rule.
ind_means <- ny_data %>% 
  group_by(Industry) %>% 
  summarise(mean_emp = mean(Employees), emp_sd = sd(Employees))
ind_means$emp_sd[is.na(ind_means$emp_sd)] <- 0
ind_means
## # A tibble: 25 x 3
##    Industry                     mean_emp emp_sd
##    <fct>                           <dbl>  <dbl>
##  1 Advertising & Marketing          38.2   24.2
##  2 Business Products & Services    102.   122. 
##  3 Computer Hardware                44      0  
##  4 Construction                     29.4   22.4
##  5 Consumer Products & Services     36.5   28.1
##  6 Education                        49.1   28.2
##  7 Energy                          116.    23.8
##  8 Engineering                      53.5   39.8
##  9 Environmental Services          155    134. 
## 10 Financial Services               88     68.9
## # … with 15 more rows
ggplot(ind_means, aes(x=reorder(Industry, mean_emp),y=mean_emp)) +
  geom_bar(stat='identity', color = 'black', fill='lightgray') +
  geom_errorbar(aes(ymin = mean_emp - emp_sd, ymax = mean_emp + emp_sd), width=0.2) +
  theme(legend.position="none") +
  ylab('Mean Employees')+ xlab('Industry')+ 
  coord_flip() +
  theme_classic()

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.

# Answer Question 3 here
q3_data<-inc %>% 
  select (Revenue, Industry, Employees) %>% 
  group_by(Industry) %>%
  summarise(total_revenue = sum(Revenue), total_employee = sum(Employees)) %>%
  mutate(revenue_employee = total_revenue / total_employee/1000) %>% 
  arrange (revenue_employee)

q3_data <- q3_data[complete.cases(q3_data$Industry), ]
q3_data <- q3_data[complete.cases(q3_data$total_employee), ]

q3<-ggplot(q3_data, aes(x=reorder(Industry, revenue_employee), y=revenue_employee)) +
  geom_bar(stat="identity")+
  theme_bw()+
  geom_col(aes(fill = revenue_employee)) + 
  geom_point(size=0.5, colour = "red") +
  scale_fill_gradient2(low = "white", high = "red") + 
  coord_flip() + 
  ggtitle ("Revenue Generated Per Employee By Industry") + ylab("Revenue Per Employee, in thousands") + 
  theme(legend.position="none") +
  theme(axis.title.y=element_blank())+
  theme(text = element_text(size = 8, color = "black"))

q3