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 110 Consulting : 1 Min. : 0.340
## 1st Qu.:1252 11thStreetCoffee.com : 1 1st Qu.: 0.770
## Median :2502 123 Exteriors : 1 Median : 1.420
## Mean :2502 1st American Systems and Services: 1 Mean : 4.612
## 3rd Qu.:3751 1st Equity : 1 3rd Qu.: 3.290
## Max. :5000 1-Stop Translation USA : 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:
#Quick check on the type of columns i'm deailng with
sapply(inc, class)
## Rank Name Growth_Rate Revenue Industry Employees
## "integer" "factor" "numeric" "numeric" "factor" "integer"
## City State
## "factor" "factor"
#Always check for sparsity and existince of NAs
unlist(lapply(inc, function(x) {sum(is.na(x))}))
## Rank Name Growth_Rate Revenue Industry Employees
## 0 0 0 0 0 12
## City State
## 0 0
#Always check for sparsity and existince of nulls
unlist(lapply(inc, function(x) {sum(is.null(x))}))
## Rank Name Growth_Rate Revenue Industry Employees
## 0 0 0 0 0 0
## City State
## 0 0
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)
inc_tmp <- inc
inc_tmp$State <- factor(inc_tmp$State, rev(levels(inc_tmp$State)))
png(filename = "Figure1.png", height = 960, width = 480, units="px")
g <- ggplot(data = inc_tmp, aes(x = State)) + geom_bar(fill="steelblue") + coord_flip() + 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:
Note, I have interpreted this to mean that we wish to find the state with the 3rd most companies before we separate out complete cases. To separate out complete cases first, we would simply have to just perform that operation at the beginning of this chunk. Also, i’m assuming we only care that the data is complete for the columns we are using, rather than the entire row having complete data.
Additionally, I was not sure if I should provide a graph that simply excluded the outliers from the visualization or if outliers should be excluded altogether. I believe that outliers should just be excluded from the visualization since the barplots would be resized (and not accurately represent the data) if they were removed. Therefore, I only excluded outliers from being shown in the plots. Note, the alternative option is provided, but not run or shown, below as well.
suppressWarnings(suppressMessages(library(dplyr)))
suppressWarnings(suppressMessages(library(tidyr)))
state <- inc %>% group_by(State) %>% summarize(RowCount = n()) %>% arrange(desc(RowCount))
inc_tmp2 <- inc[(complete.cases(inc[,c("Industry", "Employees", "State")]) & inc$State == state[3,1][[1]]),]
inc_tmp2_summary <- inc_tmp2 %>% group_by(Industry) %>% summarize(iqr = IQR(Employees), q1 = quantile(Employees)[2], median_val = quantile(Employees)[3], mean_val = mean(Employees), q3 = quantile(Employees)[4]) %>% mutate(low_limit = q1 - 1.5 * iqr, high_limit = q3 + 1.5 * iqr)
remove_outliers <- function(x, y) {
ll <- inc_tmp2_summary[inc_tmp2_summary$Industry==x,c("low_limit")][[1]]
hl <- inc_tmp2_summary[inc_tmp2_summary$Industry==x,c("high_limit")][[1]]
bol_val <- ifelse(y < ll, "N",
ifelse(y > hl, "N", "Y"))
return(bol_val)
}
inc_tmp2$Keep <- mapply(remove_outliers, inc_tmp2$Industry, inc_tmp2$Employees)
inc_tmp2_max <- round(max(inc_tmp2[inc_tmp2$Keep=="Y",c("Employees")], inc_tmp2_summary$mean_val) / 1000, 1) * 1000 + 100
inc_tmp2$Industry <- factor(inc_tmp2$Industry, levels=inc_tmp2_summary$Industry[order(inc_tmp2_summary$mean_val)])
png(filename = "Figure2.png", height = 520, width = 1020, units="px")
g <- ggplot(inc_tmp2, aes(x=Industry, y=Employees)) + geom_boxplot(fill="steelblue", color = "black", outlier.shape = NA) + labs(y = "Employee Distribtion (Without Outliers)", x = "Industries") + ggtitle(paste(state[3,1][[1]], "Firms in", "Inc. Magazine 5,000 Fastest Growing Companies")) + theme(panel.background = element_rect(fill = "white"), panel.grid.major.x = element_line(color = "lightgrey"), axis.title = element_text(size=14, color="grey55"), axis.text = element_text(size=12, color = "grey55"), plot.title = element_text(size=14, color = "grey55", hjust=0.5)) + coord_flip(ylim = c(0, inc_tmp2_max)) + scale_y_continuous(breaks = seq(0, inc_tmp2_max, by = 100)) + stat_summary(fun.y=mean, colour="darkgreen", geom="point", shape=18, size=3) + annotate("text", x = 5, y = 600, label = "Averages represented as green diamonds", color="grey55")
plot(g)
garbage <- dev.off()
Note, it is not correct to simply cutoff outliers in box plots using limits in scale_y_continuous, because the boxplots themselves will resize based on the visible data. In order to set a limit without rescaling the plots, coord_cartesian should be used. Here is the relevant stackoverflow post that I found when I was searching for a solution. However, for boxplots specifically, this solution does not work and the limits should be set via the ylim option of coord_flip directly.
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_tmp3 <- inc[complete.cases(inc[,c("Industry", "Employees", "Revenue")]),] %>% group_by(Industry) %>% summarize(TotalEmployees=sum(Employees), TotalRevenue=sum(Revenue)) %>% mutate(RevPerEmp=TotalRevenue/TotalEmployees)
inc_tmp3$Industry <- factor(inc_tmp3$Industry, levels=inc_tmp3$Industry[order(inc_tmp3$RevPerEmp)])
png(filename = "Figure3.png", height = 520, width = 1020, units="px")
g <- ggplot(inc_tmp3, aes(x=Industry, y=RevPerEmp)) + geom_bar(stat="identity", fill="steelblue") + coord_flip(ylim = c(0, 1250000)) + labs(y = "Revenue Per Employee (Millions)") + ggtitle("Inc. Magazine 5,000 Fastest Growing Companies") + theme(plot.title = element_text(hjust = 0.5)) + theme(panel.background = element_rect(fill = "white"), panel.grid.major.x = element_line(color = "lightgrey")) + theme(axis.text = element_text(size=12, color = "grey55"), axis.title = element_text(size=14, color = "grey55"), title = element_text(size=14, color = "grey55")) + scale_y_continuous(breaks = c(0, 250000, 500000, 750000, 1000000, 1250000), labels = formattermillion)
plot(g)
garbage <- dev.off()