Last active
October 22, 2021 23:56
-
-
Save erictleung/1216e9a75c1a6c1a2cbf176313dcd3a1 to your computer and use it in GitHub Desktop.
Google Trends plot for popular TV shows
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
# https://rstudio-pubs-static.s3.amazonaws.com/155168_61e1f687681d44e4988ce28b7f6ec13b.html | |
# https://www.leehbi.com/blog/2019-06-04-Google-Trends-with-R | |
library("dplyr") | |
library("ggplot2") | |
library("gtrendsR") | |
library("extrafont") | |
loadfonts(device = "win") | |
# Define search terms | |
terms <- c( | |
"Squid Game", | |
"Game of Thrones", | |
"Tiger King", | |
"Stranger Things", | |
"The Mandalorian" | |
) | |
a_pal <- RColorBrewer::brewer.pal(length(terms), "Dark2") | |
# Gather data | |
res <- gtrends(terms) | |
# Polish | |
hits_tbl <- res$interest_over_time %>% | |
mutate(hits = if_else(hits == "<1", "0", hits), | |
hits = as.numeric(hits), | |
date = as.Date(date)) %>% | |
tibble() | |
# Plot | |
hits_tbl %>% | |
ggplot(aes(x = date, y = hits, color = keyword)) + | |
geom_line(size = 1) + | |
theme_minimal() + | |
scale_color_brewer(palette = "Dark2") + | |
scale_x_date(date_labels = "%Y", | |
breaks = seq.Date(as.Date("2017-01-01"), | |
as.Date("2021-11-01"), | |
by = "year")) + | |
labs(title = '"Squid Game" Between "Stanger Things" and "Game of Thrones" Popularity', | |
subtitle = "Google Trends Data 2017 to 2021", | |
caption = "Source: Google Search Trends") + | |
theme(axis.title.x = element_blank(), | |
axis.title.y = element_blank(), | |
text = element_text(family = "Lucida Sans", size = 14), | |
legend.position = "none") + | |
geom_text(x = as.Date("2018-04-15"), | |
y = 80, | |
label = '"Game of Thrones"', | |
size = 5, | |
color = a_pal[1]) + | |
geom_text(x = as.Date("2021-06-15"), | |
y = 72.5, | |
label = '"Squid Game"', | |
size = 5, | |
color = a_pal[2]) + | |
geom_text(x = as.Date("2018-06-15"), | |
y = 45, | |
label = '"Stranger Things"', | |
size = 5, | |
color = a_pal[3]) + | |
geom_text(x = as.Date("2020-12-15"), | |
y = 15, | |
label = '"The Mandalorian"', | |
size = 5, | |
color = a_pal[4]) + | |
geom_text(x = as.Date("2020-05-20"), | |
y = 30, | |
label = '"Tiger King"', | |
size = 5, | |
color = a_pal[5]) | |
ggsave("squid_game_trends_size.png", bg = "white", width = 9.97, height = 4.84) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment