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/destination4debabrata/CUNY-Assignments/master/DATA%20608%2001%5B46846%5D/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:
Structure of data
str(inc)
## 'data.frame': 5001 obs. of 8 variables:
## $ Rank : int 1 2 3 4 5 6 7 8 9 10 ...
## $ Name : Factor w/ 5001 levels "(Add)ventures",..: 1770 1633 4423 690 1198 2839 4733 1468 1869 4968 ...
## $ Growth_Rate: num 421 248 245 233 213 ...
## $ Revenue : num 1.18e+08 4.96e+07 2.55e+07 1.90e+09 8.70e+07 ...
## $ Industry : Factor w/ 25 levels "Advertising & Marketing",..: 5 12 13 7 1 20 10 1 5 21 ...
## $ Employees : int 104 51 132 50 220 63 27 75 97 15 ...
## $ City : Factor w/ 1519 levels "Acton","Addison",..: 391 365 635 2 139 66 912 1179 131 1418 ...
## $ State : Factor w/ 52 levels "AK","AL","AR",..: 5 47 10 45 20 45 44 5 46 41 ...
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 se
## Rank 1853.25 1.0e+00 5.0000e+03 4.9990e+03 0.00 -1.20 20.41
## Name* 1853.25 1.0e+00 5.0010e+03 5.0000e+03 0.00 -1.20 20.42
## Growth_Rate 1.22 3.4e-01 4.2148e+02 4.2114e+02 12.55 242.34 0.20
## Revenue 10674720.00 2.0e+06 1.0100e+10 1.0098e+10 22.17 722.66 3401441.44
## Industry* 8.90 1.0e+00 2.5000e+01 2.4000e+01 -0.10 -1.18 0.10
## Employees 53.37 1.0e+00 6.6803e+04 6.6802e+04 29.81 1268.67 19.16
## City* 604.90 1.0e+00 1.5190e+03 1.5180e+03 -0.04 -1.26 6.24
## State* 19.27 1.0e+00 5.2000e+01 5.1000e+01 0.12 -1.46 0.22
View sample number of rows and columns, variable types
glimpse(inc)
## Observations: 5,001
## Variables: 8
## $ Rank <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ...
## $ Name <fct> Fuhu, FederalConference.com, The HCI Group, Bridger, Da...
## $ Growth_Rate <dbl> 421.48, 248.31, 245.45, 233.08, 213.37, 179.38, 174.04,...
## $ Revenue <dbl> 1.179e+08, 4.960e+07, 2.550e+07, 1.900e+09, 8.700e+07, ...
## $ Industry <fct> Consumer Products & Services, Government Services, Heal...
## $ Employees <int> 104, 51, 132, 50, 220, 63, 27, 75, 97, 15, 149, 165, 25...
## $ City <fct> El Segundo, Dumfries, Jacksonville, Addison, Boston, Au...
## $ State <fct> CA, VA, FL, TX, MA, TX, TN, CA, UT, RI, VA, CA, FL, SC,...
DT::datatable(inc, options = list(pagelength=5))
Total Revenue by Industry
# Insert your code here, create more chunks as necessary
inc %>%
group_by(Industry) %>%
summarise(Total_Revenue = sum(Revenue)) %>%
arrange(desc(Total_Revenue)) %>%
datatable()
Total Employees by State
inc[is.na(inc)] <- 0
inc %>%
group_by(State) %>%
summarise(Total_Employees = sum(Employees)) %>%
arrange(State) %>%
datatable()
Company with Largest Revenue by State
inc %>%
group_by(State) %>%
arrange(desc(Revenue)) %>%
summarise(Top_Company = first(Name), Company_Revenue = first(Revenue)) %>%
datatable()
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
inc %>%
group_by(State) %>%
summarise(No_Companies = n()) %>%
arrange(desc(No_Companies)) %>%
ggplot(aes(x = reorder(State, No_Companies), y = No_Companies)) +
geom_bar(stat="identity", fill="firebrick2", width=0.5) +
coord_flip() +
labs(title="Amount of Fastest Growing Companies by State", subtitle="count vs. State", x="State", y="Count") #+
#theme_grey(base_size = 8) +
#scale_y_continuous(expand=c(0,0))
# Creating the ggplot for top 10 states
top10 <- inc %>%
count(State, sort = TRUE) %>%
head(10)
top10$State <- factor(top10$State, levels = top10$State[order(top10$n)])
ggplot(top10, aes(State,n)) +
geom_bar(stat="identity", fill='steelblue') +
coord_flip() +
ylab("Count") +
theme_minimal() +
ggtitle("Number of Fastest Growing Companies Per State - Top 10") +
geom_text(aes(label=n), vjust=0.3, hjust=1.6, color="white", size=3.5)
inc1 <- inc
inc1$State <- factor(inc1$State, rev(levels(inc1$State)))
png(filename = "Figure.png", height = 960, width = 480, units="px")
g <- ggplot(data = inc1, aes(x = State)) +
geom_bar(fill="steelblue") +
coord_flip() +
#scale_x_discrete(limits = c(0, 30)) +
scale_y_continuous(limits = c(0, 800)) +
labs(y = "Count") +
ggtitle("Inc. Magazine 5,000 Fastest Growing Companies") +
theme(panel.background = element_rect(fill = "white"),
panel.grid.major.x = element_line(color = "lightgrey"),
axis.text = element_text(size=12, color = "grey55"),
axis.title = element_text(size=14, color = "grey55"),
plot.title = element_text(size=14, color = "grey55", hjust=0.5))
plot(g)
garbage <- dev.off()
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
third_state <- inc %>%
group_by(State) %>%
summarise(No_Companies = n()) %>%
arrange(desc(No_Companies)) %>%
summarise(value = nth(State, 3))
paste0("3rd Most Employed State:",third_state[[1, 1]])
## [1] "3rd Most Employed State:NY"
inc[complete.cases(inc), ] %>%
filter(State == third_state[[1, 1]]) %>%
group_by(Industry) %>%
summarise(No_of_Employees = sum(Employees)) %>%
arrange(desc(No_of_Employees)) %>%
ggplot(aes(x = reorder(Industry, No_of_Employees), y = No_of_Employees)) +
geom_bar(stat="identity") +
coord_flip() +
labs(title=paste("Most Employed Companies in", third_state[[1, 1]], "by Industry"))
inc[complete.cases(inc), ] %>%
filter(State == third_state[[1, 1]]) %>%
ggplot(aes(Industry, Employees)) +
geom_boxplot() +
coord_flip() +
labs(title ="New York Employment Overview by Industry") +
geom_boxplot(outlier.shape=NA) +
scale_y_continuous(limits = quantile(inc[complete.cases(inc), ]$Employees, c(0.01, 0.99)))
inc[complete.cases(inc), ] %>%
filter(State == 'NY') %>%
group_by(Industry) %>%
summarize(meanEmployment=mean(Employees),medianEmployment=median(Employees)) %>%
gather('Metric','Value',2:3) %>%
ggplot(aes(x=Industry,y=Value)) +
geom_bar(stat='identity',aes(fill=Metric),position='dodge') +
coord_flip() +
labs(title='Total employed by Industry in NY')+ylab('Employees')
Business Products & Services appears to be an outlier. Upon checking the average difference between industry means, we may be able to regulate the outlier.
third.state.table <- inc[complete.cases(inc), ] %>%
filter(State == 'NY') %>%
group_by(Industry) %>%
summarize(meanEmployment=mean(Employees), medianEmployment=median(Employees))
pivot_third.state.table <- third.state.table %>%
gather(property, count, meanEmployment, medianEmployment)
state.outlier <- pivot_third.state.table %>% filter(property == "meanEmployment")
state.outlier <- state.outlier[-c(2),] # drop the outlier
mean(diff(sort(state.outlier$count))) # calculate the average difference
## [1] 26.49105
max(diff(sort(state.outlier$count)))
## [1] 191.6224
As can be seen from above, the average difference between consecutive leading industries is 26.49105, with a max of 191.6224. With this in mind, we can cap the outlier at ~200 more than the second-highest.
third.state.edited <- pivot_third.state.table
third.state.edited[2,3] <- 815
ggplot(third.state.edited, aes(x=reorder(Industry, count), y=count)) +
geom_bar(stat="identity", position="dodge", aes(fill=property)) +
coord_flip() +
scale_fill_manual(values=c("lightsteelblue4", "lightsteelblue2"), guide=guide_legend(reverse=T)) +
scale_y_continuous(expand=c(0,0))
par(mfrow=c(1,2))
# Create a plot showing average employment by industry for companies in the state
ggplot(third.state.table %>% mutate(Industry = fct_reorder(Industry, meanEmployment)) , aes(x=Industry,y=meanEmployment, fill=Industry)) +
geom_bar(stat="identity") +
ylab('Mean Employment by Industry') +
#coord_flip() +
scale_fill_grey(start=0.8, end=0.1) +
theme(legend.position='none') +
theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))
# Create a plot showing median employment by industry for companies in the state
ggplot(third.state.table %>% mutate(Industry = fct_reorder(Industry, medianEmployment)), aes(x=Industry,y=medianEmployment, fill=Industry)) +
geom_bar(stat="identity") +
ylab('Median Employment by Industry') +
#coord_flip() +
scale_fill_grey(start=0.8, end=0.1) +
theme(legend.position='none') +
theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))
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.
inc[is.na(inc)] <- 0
inc %>%
group_by(Industry) %>%
summarise(Employee_Revenue = sum(Revenue)/sum(Employees)) %>%
arrange(desc(Employee_Revenue)) %>%
ggplot(aes(x = reorder(Industry, Employee_Revenue), y = Employee_Revenue, fill = Employee_Revenue)) +
geom_bar(stat="identity") +
coord_flip() +
labs(title ="Revenue Per Employee by Industry", ylab="Industry") +
scale_fill_gradient(low = "black", high = "darkgreen") +
theme(legend.position = "none")
inc3 <- inc[complete.cases(inc),] %>%
group_by(Industry) %>%
summarize(total_employees=sum(Employees), total_revenue=sum(Revenue), growth_rate=mean(Growth_Rate))
inc3$avgRev = inc3$total_revenue/inc3$total_employees
compDF = inc3[!inc3$Industry=='Computer Hardware' & !inc3$Industry=='Human Resources',]
compDF$scaledAR = scale(compDF$avgRev)
ggplot(compDF,aes(x=reorder(Industry,scaledAR),y=scaledAR,fill=growth_rate)) +
geom_bar(stat="identity") +
coord_flip()
# Add Revenue-Per-Employee variable
RPE = inc[complete.cases(inc), ] %>% mutate(RevPerEmp = Revenue/Employees)
# Remove extreme outliers
RPEoutliers = RPE$RevPerEmp %in% boxplot.stats(RPE$RevPerEmp, coef = 1.5)$out
RPEoutclean = RPE[!RPEoutliers, ]
# Revenue/Employee vs Industry
ggplot(RPEoutclean, aes(x = reorder(Industry, RevPerEmp, FUN = mean), y = RevPerEmp)) +
geom_boxplot(outlier.shape = NA) +
ylab("Revenue per Employee") +
xlab("Industry")+
coord_flip()+
stat_summary(fun.y=mean, colour="blue", geom="point", show_guide = FALSE)
inc3 = inc[inc$Employees > 0, ]
inc3$Revperemp <- with(inc3, Revenue/Employees)
dfSubset <- aggregate(inc3$Revperemp, list(Industry = inc3$Industry), mean)
dfSubset$Legend <- paste(dfSubset$Industry, round(dfSubset$x/1000,0), 'K', sep=' ')
ggplot(dfSubset, aes(area = x, fill = Industry, label = Legend)) +
geom_treemap(show.legend = FALSE, na.rm = TRUE, stat="identity", layout="squarified") +
geom_treemap_text(fontface = "italic", colour = "white", place = "centre",
grow = TRUE)
In this case, we have an outlier: Computer Hardware. Thus, computer hardware has the potential for the most revenue per employee, but a safer bet would probably be energy, because of its higher growth rate.
inc3 <- inc %>%
mutate(Revenue_Per_Employee = Revenue/Employees) %>%
group_by(Industry) %>%
#summarise(Employee_Revenue = sum(Revenue)/sum(Employees)) %>%
arrange(desc(Revenue_Per_Employee))
ggplot(inc3, aes(x=Industry, y=Revenue_Per_Employee, fill=Industry)) +
geom_boxplot() +
coord_flip() +
theme(legend.position='none') +
ylab("Revenue Per Employee")
ggplot(inc3, aes(x=Industry, y=Revenue_Per_Employee, fill=Industry)) +
geom_boxplot() +
scale_y_continuous(trans='log10') +
coord_flip() +
theme(legend.position='none') +
ylab("Revenue Per Employee - Logarithmic Transformation Base 10")
ggplot(inc3, aes(x=Industry, y=Revenue_Per_Employee, fill=Industry)) +
geom_violin() +
scale_y_continuous(trans='log10') +
coord_flip() +
theme(legend.position='none') +
ylab("Revenue Per Employee - Logarithmic Transformation Base 10") +
ggtitle("Violin Plot of Revenue Per Employee by Industry")