Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanpraski/319dba26b47952091bcbd2988c70ca6f to your computer and use it in GitHub Desktop.
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.
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()
@ryanpraski
Copy link
Author

image
image

@ryanpraski
Copy link
Author

+ 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