source: https://www.r-bloggers.com/analyzing-google-trends-data-in-r-2/ and https://rpubs.com/PChristensen/307008
install.packages(“gtrentsR”) # if this doesn’t work, try the followin code to install the necessary package devtools::install_github(‘PMassicotte/gtrendsR’)
library(gtrendsR)
library(reshape2)
library(ggplot2)
library(maps)
library(ggmap)
retrieves the global search history since 2004 for UBI
UBI01 = gtrends(c("Universal Basic Income","basic income"), gprop = "web",time="all")
UBI02 = gtrends(c("basic income"), gprop = "web",time="all")
UBI03 = gtrends(c("basic income"), gprop = "web",time="all", geo = c("US")) # specify the region. In this case, US
to see the overall trends
plot(UBI01)
plot(UBI02)
plot(UBI03)
Now, let’s compare the amount of interest in Basic income for each US state.
UBI03 = UBI03$interest_by_region
UBI03$region = sapply(UBI03$location,tolower)
states_map <- map_data("state") # state level map data
UBI03Merged = merge(states_map,UBI03,by="region")
regionLabels <- aggregate(cbind(long, lat) ~ region, data=UBI03Merged,
FUN=function(x) mean(range(x)))
Mapping
Plot=ggplot() +
geom_polygon(data=UBI03Merged,aes(x=long,y=lat,group=group,fill=hits),colour="white") +
scale_fill_continuous(low="thistle2",high="darkred",guide="colorbar",trans="log10") +
geom_text(data=regionLabels, aes(long, lat, label = region), size=2) +
theme_bw() +
coord_fixed(1.3) +
labs(title="Google search interest for UBI in each state")
Plot