Required Packages

library(httr2)
library(jsonlite)
library(ggplot2)
library(scales)
library(lubridate)
library(knitr)

Tutorial 1: Single Keyword — Brand Search Interest

Data Status

if (trend_result$success == TRUE) {
  cat("Google Trends data was successfully retrieved.")
} else {
  cat("Google Trends data could not be retrieved from Posit Cloud.")
  cat("\n\nStatus code:", trend_result$status_code)
  cat("\n\nA status code of 429 means Google Trends is rate-limiting requests from this cloud environment.")
}
## Google Trends data could not be retrieved from Posit Cloud.
## 
## Status code: 429
## 
## A status code of 429 means Google Trends is rate-limiting requests from this cloud environment.

Preview the Data

head(iot)
## [1] date hits
## <0 rows> (or 0-length row.names)

Plot Search Interest

if (nrow(iot) > 0) {
  
  ggplot(iot, aes(x = date, y = hits)) +
    geom_line(color = "#00704A", linewidth = 1) +
    geom_smooth(
      method = "loess",
      se = TRUE,
      color = "#1E3932",
      fill = "#D4E9E2",
      alpha = 0.3
    ) +
    scale_x_date(date_labels = "%b %Y", date_breaks = "2 months") +
    labs(
      title = "Google Search Interest: Starbucks",
      subtitle = "United States | Past 5 years | Web Search",
      x = NULL,
      y = "Relative Interest (0-100)",
      caption = "Source: Google Trends"
    ) +
    theme_minimal(base_size = 12) +
    theme(
      plot.title = element_text(face = "bold", size = 14),
      plot.subtitle = element_text(color = "gray50"),
      axis.text.x = element_text(angle = 30, hjust = 1)
    )
  
} else {
  
  plot.new()
  text(
    x = 0.5,
    y = 0.5,
    labels = "Google Trends request was rate-limited by Posit Cloud.\nStatus code: 429",
    cex = 1.1
  )
  
}

References

Google Trends. (2024). Google Trends Tutorials [YouTube series]. Google Search Central. https://developers.google.com/search/blog/2024/09/google-trends-tutorials

Massicotte, P., & Eddelbuettel, D. (2023). gtrendsR: Perform and Display Google Trends Queries [R package]. https://cran.r-project.org/package=gtrendsR

Chan, M. (2019). Vignette: Google Trends with the gtrendsR package. https://martinctc.github.io/blog/vignette-google-trends-with-gtrendsr/