Last active
April 6, 2017 20:56
-
-
Save ryanpraski/5070e1ded4c2e20ec00171f94a774562 to your computer and use it in GitHub Desktop.
R Script to create a heatmap the visualizes Google Analytics page scroll depth tracking. Tutorial here: http://www.ryanpraski.com/r-heatmap-tutorial-for-google-analytics/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(googleAnalyticsR) | |
library(ggplot2) | |
#Authorized Google Analytics R- this will open a webpage | |
#You must be logged into your Google Analytics account on your web browser | |
ga_auth() | |
#Use google_analytics_account_list() to find the viewId. Make sure to replace this with your viewId. | |
my_id <- 94579701 | |
#Page View Query | |
df1 <- google_analytics_4(my_id, | |
date_range = c("365daysAgo", "yesterday"), | |
metrics = c("pageviews"), | |
dimensions = c("pagePath"), | |
anti_sample = TRUE) | |
#Event Query this assumes that you are tracking % page scroll and #disqus_thread. | |
#Change the filtersExpression eventLable to match your scroll depth data | |
df <- google_analytics_4(my_id, | |
date_range = c("365daysAgo", "yesterday"), | |
metrics = c("totalEvents"), | |
dimensions = c("pagePath","eventLabel"), | |
filtersExpression = c("ga:eventLabel=~%|#disqus"), | |
anti_sample = TRUE) | |
#Merge the page and scroll depth data into a single data frame | |
#Order page by top 15 pageviews and only include top 15 combined dataframe | |
df2<-merge(head(df1[order(-df1$pageviews),],n=15),df) | |
#Add a new column to that shows the percent of pageviews reaching each scroll depth for each page | |
df2$percent <-round(df2$totalEvents/df2$pageviews,digits = 2) | |
#Order pagePath by pageviews for heatmap | |
#And convert pagePath to a factor variable so the ggplot heatmap follows the sort order | |
df2$pagePath <- factor(df2$pagePath, levels = df2$pagePath[order(df2$pageview)]) | |
#Heatmap ggplot | |
df2 %>% | |
ggplot(aes(x=eventLabel, y=pagePath, fill=percent)) + | |
geom_tile() + | |
scale_fill_continuous(low = 'white', high = 'red') + | |
scale_x_discrete(limits=c('25%','50%','75%', '#disqus_thread', '100%')) + | |
scale_y_discrete()+ | |
theme_bw() + | |
theme(panel.grid.major = element_blank()) |
Author
ryanpraski
commented
Apr 6, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment