Interactive Google Analytics Charting in R with

r Dec 18, 2016

We will walk around creating an interactive line chart in R with Google Analytics data and publishing online at  If you haven’t setup Rstudio please read my previous post here.  For the charting part, we will be using, so let’s start by installing the required libraries: 

Install Plotly package.


Then copy paste the code below:

## loading packages

##for refreshing token

##Charting script ## Do replace with your profileid below
ga_data <- google_analytics_4("ga:634243597", 
                              date_range = c("2016-11-01","2016-11-30"),
                              metrics = c('sessions'),
                              order = order_type("date", "ASCENDING")

## Defining X and Y axis
Sessions <- c(ga_data$sessions)
Date <- c(ga_data$date)

## Draw chart
plot_ly(x = ~Date, y = ~Sessions, type = 'scatter', mode = 'lines')

Execute Script

Be sure to replace with your Google Analytics profileId.  And we will get visualization like below.


Configure API

Now, let’s publish the chart to by configuring API settings for this. Use the code below to setup:

## user name

## API key

You can generate API key here at settings.

Publishing Chart

To publish use:

p <- plot_ly(x = ~Date, y = ~Sessions, type = 'scatter', mode = 'lines')
plotly_POST(p, filename = "line-chart")


Below is the live embedded chart and link.




Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.