Created
June 1, 2017 17:20
-
-
Save ryanpraski/319dba26b47952091bcbd2988c70ca6f to your computer and use it in GitHub Desktop.
Graph Google Analytics session data by month and year. Create a bar graph or line graph of Google Analytics sessions using googleAnalyticsR to pull data, dplyr to group data by month and year and ggplot2 to graph data.
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) | |
library(dplyr) | |
#Authorize Google Analytics R- this will open a webpage | |
#You must be logged into your Google Analytics account on your web browser | |
ga_auth() | |
#Use my_accounts to find the viewId. Make sure to replace this with your viewId. | |
my_id <- 94579701 | |
#set date variables for dyanmic date range | |
start_date <- "1000daysAgo" | |
end_date <- "yesterday" | |
#Session Query - Uses start_date and end_date | |
df <- google_analytics_4(my_id, | |
date_range = c(start_date, end_date), | |
metrics = c("sessions"), | |
dimensions = c("date")) | |
##add in year month columns to dataframe | |
df$month<-format(df$date,"%m") | |
df$year<-format(df$date,"%Y") | |
#sessions by month by year using dplyr then graph using ggplot2 bar graph | |
df %>% | |
group_by(year,month) %>% | |
summarize(sessions=sum(sessions)) %>% | |
#print table steps by month by year | |
print (n=100) %>% | |
#graph data by month by year | |
ggplot(aes(x=month, y=sessions, fill=year)) + | |
geom_bar(position='dodge', stat='identity') | |
#sessions by month by year using dplyr then graph using ggplot2 line graph | |
df %>% | |
group_by(year,month) %>% | |
summarize(sessions=sum(sessions)) %>% | |
#print table steps by month by year | |
print (n=100) %>% | |
#graph data by month by year | |
ggplot(aes(x=month, y=sessions, group=year, color=year)) + | |
geom_line() |
Author
ryanpraski
commented
Jun 1, 2017
+ scale_x_discrete(labels=month.abb)
to ggplot to add month abbreviation instead of month number in graph.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment