Trending Tweet Locations on Map with R

Arindam Mitra
5 min readFeb 3, 2023

--

With TweeterR Package

We have seen how to read tweets with TwitteR package in last post. Continuing with that, here we find the locations from where the tweets are trending, and plot them on a map.

Reproduced from my old blog from Jan 2014.

Get the trending locations

We first need to catch the trending tweet locations with twitteR’s availableTrendLocations(). This functions returns a data.frame with 3 columns — name (city name), country (country), and woeid (Yahoo! Where On Earth ID).

Next we add longitude and latitude to this data.frame before doing any further analysis. Though this information may be redundant (as we could have used city name directly to mark them on the map), but in certain cases it may be helpful.

We can use ggmap library’s geocode() for finding longitude and latitude corresponding to each city in the data.frame.

# extract the locations from where the trending tweets are originated
trendLocations <- availableTrendLocations(cainfo="cacert.pem")
# we get a data.frame with three columns - name, country and woeid

# ggmap librarys' geocode() returns lon-lat information
library(ggmap)
# add two more columns to the data.frame - lon-lat value of each city
trendLocationsCity<-cbind(trendLocations,
lon=geocode(trendLocations$name)[1],
lat=geocode(trendLocations$name)[2])

# number of trending tweets from various cities, aggregated by the country it belongs to
library(plyr)
# plyr's ddply() creates a data.frame with country names, and count of aggregated tweets
trendLocationsCountry <- ddply(trendLocations, .(country), summarize, count=length(country))

# add lon-lat value of countries to the data.frame
# note that the lon-lat information may be redundant, as many libraries can directly work with
# the country/ city names, and may not require these values
trendLocationsCountry<-cbind(trendLocationsCountry,
lon=geocode(trendLocationsCountry$country)[1],
lat=geocode(trendLocationsCountry$country)[2])
data.frame of trending cities and countries.
data.frame of trending countries aggregated by cities.

There are many possible ways to plot maps in R. We explore 4 of them in this post.

Plot World Map with maps package

It’s a basic yet useful package. At times when you want have more control over the map’s appearance, this package may not be the best option.

Here we plot a world map with the cities with trending tweets marked as blue dots.

library(maps)
# draw a world map
map("world", fill=TRUE, col="white", bg="lightblue", ylim=c(-60, 90), mar=c(0,0,0,0))

# add a layer with the cities on top of the world map
points(trendLocationsCity$lon,trendLocationsCity$lat, cex=0.5, col="blue", pch=16)
Trending cities — with maps package.

Plot World Map with ggplot2

ggplot2 is a very powerful graphics library in R — it capable of producing good looking plots, and more importantly offers a lot of flexibility to fine-tune the appearance and representation. We begin with a base layer of a blank map (from maps package), and add layers of spatial data on top of it.

Here we show cities with the trending tweets in the first figure, and in the next, the trending countries aggregated by cities.

library(ggplot2)

library(ggplot2)

# create a world map environment
ggWorldMap <- borders("world", colour="gray50", fill="gray80") # create a layer of borders

# create base world map layer
ggTrendMap <- ggplot() +
ggWorldMap +
xlab("") + ylab("") #remove the x- and y-axis labels

# use the world map as base, and add a layer with the cities as blue dots
ggTrendMap + geom_point(aes(x=lon, y=lat),data=trendLocationsCity, color="blue", size=3)

# reuse the world map as base, and add a layer with countries
# the number of trending tweets is represented by the size of the dot
ggTrendMap + geom_point(aes(x=lon, y=lat, size=count),
data=trendLocationsCountry,
color="blue")
Trending Cities — with ggplot2.
Trending countries aggregated by cities — with ggplot2.

Plot World Map with ggmap

This package allows us to choose from Google Maps, OpenStreetMaps, Stamen Maps, or CloudMade Maps to be used as a base layer, and then add layers of spatial data and models with ggplot2. It can be used to show zoomed-in views with detailed landscapes, like cities and neighborhood buildings, however, it can’t zoom out to show the whole world.

As it is not possible to show the entire world map, we subset a region of interest, say US, and plot the trending cities.

library(ggmap)

# Subset US city locations
trendLocationsCityUS <- subset(trendLocationsCity, trendLocations$country=="United States")

# create a base US map layer
gmTrendMapUS <- qmap(location = 'usa', zoom = 4, maptype = 'roadmap') #draw world map

# use the US map as base, and add a layer with US cities as blue dots
gmTrendMapUS + geom_point(aes(x=lon, y=lat),
color="blue", alpha=0.8, size=5, data=trendLocationsCityUS)
Trending US cities — with ggmap.

Interactive World Map with googleVis

All the options seen so far produces static maps. But to plot a web-based interactive map, googleVis comes handy.

Here we show the number of trending tweets aggregated by the country of their origin. On mouse hover on any country, it dynamically shows the tweet count from there.

library(googleVis)

# create a map with country names and the number of tweets trending from there
# note that in gvisGeoMap(), we are passing country names, not their lon-lat values
goTrendMap <- gvisGeoMap(trendLocationsCountry, locationvar="country",
numvar="count", options=list(dataMode="regions"))

#plot the map and display in a browser
plot(goTrendMap)
Trending countries — with googleVis.

References
Stackoverflow, for R implementation
Ggmap documentation
Combining ggplot2 and Google Maps

--

--

Arindam Mitra

Intersection of Product Management and Data Analytics. I grow and monetize free-to-play mobile games.