** Original source for this assignment is from https://github.com/charleyferrari/CUNY_DATA_608/blob/master/module1/hw1.rmd

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)
summary(inc)
##       Rank          Name            Growth_Rate         Revenue         
##  Min.   :   1   Length:5001        Min.   :  0.340   Min.   :2.000e+06  
##  1st Qu.:1252   Class :character   1st Qu.:  0.770   1st Qu.:5.100e+06  
##  Median :2502   Mode  :character   Median :  1.420   Median :1.090e+07  
##  Mean   :2502                      Mean   :  4.612   Mean   :4.822e+07  
##  3rd Qu.:3751                      3rd Qu.:  3.290   3rd Qu.:2.860e+07  
##  Max.   :5000                      Max.   :421.480   Max.   :1.010e+10  
##                                                                         
##    Industry           Employees           City              State          
##  Length:5001        Min.   :    1.0   Length:5001        Length:5001       
##  Class :character   1st Qu.:   25.0   Class :character   Class :character  
##  Mode  :character   Median :   53.0   Mode  :character   Mode  :character  
##                     Mean   :  232.7                                        
##                     3rd Qu.:  132.0                                        
##                     Max.   :66803.0                                        
##                     NA's   :12

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
library(knitr)
library(xml2)
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(summarytools)
library(psych)

# For summarytools package
opts_chunk$set(results = 'asis',      
                comment = NA,
                prompt  = FALSE,
                cache   = FALSE)

st_options(plain.ascii = FALSE,        
            style        = "rmarkdown", 
            footnote     = NA,          
            subtitle.emphasis = FALSE)  

Here is a look at the frequency of the data by Industry and State.

# Print out a frequency table of the data by Industry
freq(inc$Industry, order = "freq", plain.ascii = FALSE)

Frequencies

inc$Industry
Type: Character

  Freq % Valid % Valid Cum. % Total % Total Cum.
IT Services 733 14.66 14.66 14.66 14.66
Business Products & Services 482 9.64 24.30 9.64 24.30
Advertising & Marketing 471 9.42 33.71 9.42 33.71
Health 355 7.10 40.81 7.10 40.81
Software 342 6.84 47.65 6.84 47.65
Financial Services 260 5.20 52.85 5.20 52.85
Manufacturing 256 5.12 57.97 5.12 57.97
Consumer Products & Services 203 4.06 62.03 4.06 62.03
Retail 203 4.06 66.09 4.06 66.09
Government Services 202 4.04 70.13 4.04 70.13
Human Resources 196 3.92 74.05 3.92 74.05
Construction 187 3.74 77.78 3.74 77.78
Logistics & Transportation 155 3.10 80.88 3.10 80.88
Food & Beverage 131 2.62 83.50 2.62 83.50
Telecommunications 129 2.58 86.08 2.58 86.08
Energy 109 2.18 88.26 2.18 88.26
Real Estate 96 1.92 90.18 1.92 90.18
Education 83 1.66 91.84 1.66 91.84
Engineering 74 1.48 93.32 1.48 93.32
Security 73 1.46 94.78 1.46 94.78
Travel & Hospitality 62 1.24 96.02 1.24 96.02
Media 54 1.08 97.10 1.08 97.10
Environmental Services 51 1.02 98.12 1.02 98.12
Insurance 50 1.00 99.12 1.00 99.12
Computer Hardware 44 0.88 100.00 0.88 100.00
<NA> 0 0.00 100.00
Total 5001 100.00 100.00 100.00 100.00

Here is a look at the data by using the psych library. This would be looking at variables with the mean, standard deviation, et al. 

# Growth Rate variable
describe(inc$Growth_Rate)
# Revenue variable
describe(inc$Revenue)
# Employeesvariable
describe(inc$Employees)

Because of the large values for Revenue, it would be best to represent with log.

The following groups the data by City and State in descending order by Total Revenue in log form.

inc %>%
    group_by(City, State) %>%
    summarise(totalRevenue = log(sum(Revenue))) %>%
    arrange(desc(totalRevenue))

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.

The solution below uses the forcats and ggplot2 libraries. More information about forcats is here https://forcats.tidyverse.org/. I decided to go with a bar graph where the counts are organized by state in ascending order and the Tufte theme. I had a difficult time adjusting the labels and hope to remedy this in the future.

# Answer Question 1 here

# For information about bar widths
# https://r-graphics.org/recipe-bar-graph-adjust-width
library(forcats)
library(ggplot2)
library(ggthemes)

# Used fct_rev to reverse the order because after coord_flip the least gets put on top
ggplot(inc, aes(x=fct_rev(fct_infreq(State)))) + 
    geom_bar(stat="count", width = 0.7) +
    coord_flip() +
    xlab("State") +
    ylab("Count") +
    theme_tufte() +
    ggtitle("Distribution of Companies by State") 

Question 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
library(scales)

# Get the NY data set
nyData <- inc[ which(inc$State == 'NY'), ]
# Remove incomplete records in the NY Dataset
nyData <- nyData[complete.cases(nyData), ] 
# Display a sample
head(nyData)
# Obtain the max, min, and medians based on the Employees variable
upperNY <- max(nyData$Employees)
lowerNY <- min(nyData$Employees)
medianNY <- median(nyData$Employees)

# https://ggplot2.tidyverse.org/reference/geom_boxplot.html
ggplot(nyData, aes(reorder(Industry, Employees, FUN = median), Employees)) + 
  geom_boxplot(outlier.colour = "#FF003C", 
               outlier.shape = 1) +
  coord_flip() +
  geom_hline(yintercept = median(nyData$Employees), 
             color="steelblue", 
             linetype="dashed") +
  geom_text(aes(x=2, 
            label="Overall Median for Employees", y = medianNY + 175), 
            size = 3, 
            colour="steelblue") +
  scale_y_continuous(trans = log2_trans(), limits = c(lowerNY, upperNY)) +
  xlab("Industry") +
  ylab("Number of Employees") +
  theme_tufte() + 
  ggtitle("Number of Employees by Industry in New York")

From the previous problem, NY is the state with the 3rd most companies. The above graph uses log transformations to better capture the data within upper and lower bounds. The outliers were made to appear as empty red circles.

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  

# Store the complete cases
rpeData <- inc[complete.cases(inc), ]


# Create a new dataframe for plotting. Sums of Employees and Revenue become Employees_name and Revenue_name respectively
plotrpeData <- rpeData %>%
            group_by(Industry) %>%                         
            summarise_at(vars(Employees, Revenue), list(name = sum))                

# Rename the columns for plotrpeData 
names(plotrpeData)[names(plotrpeData)=="Revenue_name"] <- "Revenue"
names(plotrpeData)[names(plotrpeData)=="Employees_name"] <- "Employees"

plotrpeData$RPE <- plotrpeData$Revenue / plotrpeData$Employees

# Sample of the dataframe
head(plotrpeData)
# Create the plot
ggplot(plotrpeData, aes(x=reorder(Industry, RPE), y=RPE/10000)) + 
    geom_bar(stat="identity", fill="#FF003C") +
    coord_flip() +
    xlab("Industry") +
    ylab("Revenue Per Employee: 1: 10k") +
    theme_tufte() +
    ggtitle("Revenue Per Employee By Industry") 

It looks like Computer Hardware, Energy, and Construction are the top three industries generate the most revenue per employee.