knitr::opts_chunk$set( collapse = TRUE, comment = "#>", warning = FALSE ) library(htmltools) library(graphTweets) library(rtweet) token <- readRDS("../twitter_token.rds") tweets <- search_tweets("#rstats", n = 1000, include_rts = FALSE, token = token, lang = "en")
What is a dynamic graph? A graph that includes an additional dimension which renders is dynamic. Here we'll create a temporal graph
Start by making the graph, see "Get Started" vignette if you do not know how to get tweets.
tweets %>% gt_edges(screen_name, mentions_screen_name, created_at) %>% gt_nodes() %>% gt_dyn() %>% gt_collect() -> net
A few things to note.
created_at
in gt_edges
as we want to know the time at which the edge is created.gt_nodes
gt_dyn
(short for "dynamic") to get the dynamic graph.Let's look at the output.
knitr::kable(head(net$edges))
The edges include the created_at
column (date time when the tweet is posted).
knitr::kable(head(net$nodes))
The nodes include start
and end
column, this is added by the gt_dyn
function; which, in effect, simply computes when the node should appear on the graph.
I use sigmajs to visualise the dynamic graph, please see the website if you want to understand the code below, being a different package I do not get into this here. In brief, I convert date time to numeric and rescale edge appearances between 0 and 10 seconds (so that the animation lasts 10 seconds), I then add 5 seconds so that the animation starts after 5 seconds (to give you a chance to see it in action).
Click the trigger to add the edges.
library(sigmajs) # convert to numeric & rescale edges <- net$edges %>% dplyr::mutate( id = 1:dplyr::n(), created_at = as.numeric(created_at), created_at = (created_at - min(created_at)) / (max(created_at) - min(created_at)), created_at = created_at * 10000 ) nodes <- net$nodes %>% dplyr::mutate( id = nodes, label = nodes, size = n ) # graph layout nodes <- sg_get_layout(nodes, edges) nodes <- sg_get_cluster(nodes, edges, colors = c("#2780e3", "#d3d3d3")) # cluster sigmajs() %>% sg_nodes(nodes, id, size, label, x, y, color) %>% sg_add_edges(edges, created_at, id, source, target, cumsum = FALSE, refresh = TRUE) %>% sg_button("add_edges", tags$i(class = "fa fa-play"), class = "btn btn-primary") %>% sg_settings(defaultNodeColor = "#1967be")
Note that you can also dynamically add nodes, much of it explained in the twinetbook.
tags$a( href = "https://twinetbook.john-coene.com/", target = "_blank", "Twinetbook" )
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.