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:
library(tidyverse)
library(ggplot2)
library(scales)
inc <- read.csv("https://raw.githubusercontent.com/charleyferrari/CUNY_DATA_608/master/module1/Data/inc5000_data.csv", header= TRUE, stringsAsFactors = 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:
The summary function provides exactly what is needed in terms of summary statistics. The function showed only the variable type for the categorical variables, so I added StringAsFactors =TRUE when building the data frames
The function provides an overall glimpse via descriptive statistics for the columns in the dataset. As we can see from the summary the dataset is dominated by IT services, followed by Business Products and Services and Advertising and Marketing companies.
# We can also use str overview of inc data frame
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 ...
Another important is to check the missing values since they might affect or skew our visualizations.
colSums(is.na(inc))
## Rank Name Growth_Rate Revenue Industry Employees
## 0 0 0 0 0 12
## City State
## 0 0
Let’s take a look at the top five industries with the highest growth rates.
top5 <-inc%>%
group_by(Industry)%>%
summarize(Avg_growth=mean(Growth_Rate))%>%
top_n(5,Avg_growth)%>%
arrange(desc(Avg_growth))
top5
## # A tibble: 5 x 2
## Industry Avg_growth
## <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
Let’s get the top 5 cities in America with the 1000 fastest growing companies
top_5_cities <- inc %>% arrange(desc(Growth_Rate)) %>% head(1000) %>% count(City, sort = TRUE) %>% head(5)
top_5_cities
## City n
## 1 New York 35
## 2 San Francisco 26
## 3 Chicago 20
## 4 Austin 19
## 5 Atlanta 17
We can Also check how many state codes are there in the data set.
unique(unlist(inc$State))
## [1] CA VA FL TX MA TN UT RI SC DC NJ OH WA ME NY CO GA IL AZ NC MD MN OK PA CT
## [26] IN MS WI WY MI MO KS OR NE AL HI NV IA KY ID AK LA DE AR NH VT NM SD ND PR
## [51] MT WV
## 52 Levels: AK AL AR AZ CA CO CT DC DE FL GA HI IA ID IL IN KS KY LA MA ... WY
We see 52 codes, the 50 states plus DC and Puerto Rico. Next we can do same for Industry column to see how many they are there and if they’re duplicate.
unique(unlist(inc$Industry))
## [1] Consumer Products & Services Government Services
## [3] Health Energy
## [5] Advertising & Marketing Real Estate
## [7] Financial Services Retail
## [9] Software Computer Hardware
## [11] Logistics & Transportation Food & Beverage
## [13] IT Services Business Products & Services
## [15] Education Construction
## [17] Manufacturing Telecommunications
## [19] Security Human Resources
## [21] Travel & Hospitality Media
## [23] Environmental Services Engineering
## [25] Insurance
## 25 Levels: Advertising & Marketing ... Travel & Hospitality
We see 25 different industry categories and none of them overlap.
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.
# Prepare the data for plotting
data <- inc %>%
group_by(State) %>%
tally() %>%
rename(count = n) %>%
arrange(desc(count))
#plot our data
g <- ggplot(data, aes(x = reorder(State, count), y = count))
g <- g + geom_bar(stat = "identity", fill = 'dodgerblue1') + coord_flip()
g <- g + ggtitle("Distribution of 5,000 Fastest Growing Companies")
g <- g + labs(subtitle = "by state", x = "state", y = "company count")
g <- g + theme(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5))
g
California, Texas, and New York appear to have the 3 fastest growing companies in the US.
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.
# First let's find state with third most companies (our data is already ordered in descendant, therefore the 3rd row)
state3rd <- data[3,"State"]
state3rd
## # A tibble: 1 x 1
## State
## <fct>
## 1 NY
# filter 3rd ranked state only
data2 <- inc[complete.cases(inc),] %>%
inner_join(state3rd, by = "State")
# Calculate the mean employees by industry
means <- aggregate(Employees ~ Industry, data2, mean)
# Calculate the maximum average employee no.
means_max <- max(means$Employees)
# prepare plot data: box plots (with outliers removed)
g <- ggplot(data2, aes(x = reorder(Industry,Employees,mean), y = Employees))
g <- g + geom_boxplot(outlier.shape = NA, show.legend=F) + coord_flip()
g <- g + labs(x = "industry", y = "employees", title="Mean Employee Size by Industry")
g <- g + labs(subtitle = "with boxplots")
g <- g + geom_point(data = means, aes(x=Industry, y=Employees), color='darkred', size = 2)
g <- g + theme(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5))
# plot data, linear scale
g <- g + scale_y_continuous(limits = c(0,means_max), breaks = seq(0, means_max, 200))
g
We can see from the graph that the mean data are highly skewed, that is there is an outlier employee count in the Business Products & Services industry that is almost 2 times greater than the second ranked industry, Consumer Products & Services. i.e. more than 100%. We can visualize the data on a logarithmic scale to scale everything down.
# plot data, log scale
g <- g + scale_y_log10(limits = c(1, means_max))
g <- g + labs(caption = "(logarithmic scale spacing)")
g <- g + theme(plot.caption = element_text(size = 8))
g
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.
# Filter by Most Revenue per employee by industry
revenue.industry <- inc %>%
filter(State== "NY") %>%
group_by(Industry) %>%
summarise(avg_revenue = mean(Revenue))
# NOw since we have the filtered data, let's put it into graph to see visualization
ggplot(revenue.industry, aes(x=reorder(Industry, avg_revenue), y=avg_revenue))+geom_bar(stat="identity", fill="#03DAC5")+coord_flip()+labs(title="Average Revenue per Employee by industry in NY", x="Industry", y="Average Revenue per Employee")
According to visualizations from Question 1, California has the most number of companies in United States. In Question 2 we dug in on the state with the 3rd most companies in the data set which is New York, and we used a box plot to show the average and/or median employment by industry for companies in NY. Box plots help visualize the distribution of quantitative values in a field. They are also valuable for comparisons across different categorical variables or identifying outliers, if either of those exist in a dataset. Finally to check the average revenue per employee by different industry in NY, we again created bar chart and found that consumer products & services has the highest average revenue per employee while IT services and business products & services are the next highest. Eduction and government services has the least average revenue per employee in NY.