graphTweets not only allows to build graphs of interactions between users. It also lets you visualise what hashtag users use in their tweets.

tweets <- search_tweets("#rstats #python", n = 1000, include_rts = FALSE, token = token, lang = "en")

The same principles follow, we simply use gt_edges_hash and pass the hashtags column as returned by rtweet. This creates a tibble of edges from screen_name to hashtags used in each tweet.

net <- tweets %>% 
  gt_edges_hash(hashtags, screen_name) %>% 
  gt_nodes() %>% 

We’ll visualise the graph with sigmajs. Let’s prepare the data to meet the library’s requirements.

  • We add id to both nodes and edges
  • We add rename a few columns to meet sigmajs’ convention
  • We color the nodes by type (hashtag or user)

Apologies for not getting into details here but sigmajs is very well documented, check the website if you want to understand it all.

edges <- net$edges
nodes <- net$nodes

edges$id <- seq(1, nrow(edges))
nodes$id <- nodes$nodes
nodes$label <- nodes$nodes
nodes$size <- nodes$n_edges
nodes$color <- ifelse(nodes$type == "user", "#0084b4", "#1dcaff")

Let’s visualise it.


sigmajs() %>% 
  sg_nodes(nodes, id, size, color, label) %>% 
  sg_edges(edges, id, source, target) %>% 
  sg_layout(layout = igraph::layout_components) %>% 
    edgeColor = "default",
    defaultEdgeColor = "#d3d3d3"
  ) %>% 

We use sg_layout to layout the graph and sg_neightbours to highlight nodes on click.