knitr::opts_chunk$set( collapse = TRUE, comment = "#>", warning = FALSE ) library(graphTweets) library(rtweet) token <- readRDS("../twitter_token.rds") tweets <- search_tweets("#rstats", n = 1000, include_rts = FALSE, token = token, lang = "en") tweets_mentions <- search_tweets("#rstats filter:mentions", n = 1000, token = token, lang = "en") #tweets$text <- iconv(tweets$text, to = "UTF-8", sub = "")
graphTweets not only allows to build graphs of interactions between users. It also lets you visualise what hashtag users use in their tweets and which hashtags are used together in the same tweets.
We can also build networks of hashtags co-mentions; when two or more hashtags are used in the same tweet they are connected on the graph.
Let's look at the hashtags associated with #rstats
tweets <- search_tweets("#rstats", n = 1000, include_rts = FALSE, token = token, lang = "en")
For this network use gt_edges_hashes
and simply pass the hashtags
column as it's all that is needed.
net <- tweets %>% gt_co_edges(hashtags) %>% gt_nodes() %>% gt_collect() c(edges, nodes) %<-% net
Then again, we'll use sigmajs
for the visualisation. Since we got tweets on #rstats
we will remove this node, it will be connected to all other hashtags. Make sure you remove it from both nodes and edges.
library(dplyr) edges <- edges %>% mutate( id = 1:n() ) %>% filter(source != "#rstats") %>% filter(target != "#rstats") nodes <- nodes %>% mutate( id = nodes, label = id, size = n ) %>% filter(id != "#rstats") %>% select(id, label, size) library(sigmajs) sigmajs() %>% sg_nodes(nodes, id, label, size) %>% sg_edges(edges, id, source, target) %>% sg_cluster( colors = c( "#0084b4", "#00aced", "#1dcaff", "#c0deed" ) ) %>% sg_layout() %>% sg_neighbours() %>% sg_settings( defaultEdgeColor = "#a3a3a3", edgeColor = "default" )
We can also build networks of co-mentions where users that are \@tagged in the same tweet are connected. We'll collect more tweets, with a slightly different queries to ensure that the tweets include \@mentions.
tweets_mentions <- search_tweets("rstats filter:mentions", n = 1000, token = token, lang = "en")
When preparing the graph we simply pass mentions_screen_name
instead of hashtags
as we did before.
net <- tweets_mentions %>% gt_co_edges(mentions_screen_name) %>% gt_nodes() %>% gt_collect() c(edges, nodes) %<-% net edges <- edges %>% mutate(id = 1:n()) nodes <- nodes %>% mutate( id = nodes, label = id, size = n ) sigmajs() %>% sg_nodes(nodes, id, label, size) %>% sg_edges(edges, id, source, target) %>% sg_cluster( colors = c( "#0084b4", "#00aced", "#1dcaff", "#c0deed" ) ) %>% sg_layout(layout = igraph::layout.fruchterman.reingold) %>% sg_neighbours() %>% sg_settings( maxNodeSize = 3, defaultEdgeColor = "#a3a3a3", edgeColor = "default" )
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.