Skip to content

Instantly share code, notes, and snippets.

@ajstewartlang
Last active July 24, 2018 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajstewartlang/c6eca4722071b318b376af13aab26c2b to your computer and use it in GitHub Desktop.
Save ajstewartlang/c6eca4722071b318b376af13aab26c2b to your computer and use it in GitHub Desktop.
animating tweets using rtweet and tidytext for extraction/tidying and gganimate for animation
#Slightly messy code - could easily be improved upon
#new version of gganimate not yet on CRAN so need to download from github with devtools package
#devtools::install_github('thomasp85/gganimate')
library(tidytext)
library(tidyverse)
library(rtweet)
library(gganimate)
library(lubridate)
rt <- search_tweets("#rstats", n = 50000, include_rts = FALSE, retryonratelimit = TRUE)
rt1 <- rt %>% unnest_tokens(word, text)
sent <- get_sentiments("bing") %>% filter(sentiment == "positive")
rt2 <- rt1 %>% mutate (day=day(created_at))
rt3 <- rt2 %>%
inner_join(sent) %>%
count(word, sentiment, day, sort = TRUE)
#work out top words anchored on day 1
top_words <- rt3 %>% filter (day==min(day)) %>% top_n(.,6)
filt_words <- rt3[grepl(paste(top_words$word,collapse="|"), rt3$word),]
word_counts <- filt_words %>% arrange(-desc(day))
word_counts %>%
filter (n > 1) %>%
mutate(word = reorder(word, n)) %>%
ggplot(aes(word, n, fill="red")) +
geom_col() +
scale_fill_discrete(guide=FALSE) +
coord_flip() +
labs(x = "Word", y="Mentions (N)", title=paste0("Top positive sentiment words in \nTweets mentioning #rstats \n{frame_time} July 2018")) +
theme(text=element_text(size=18)) +
transition_time(day) +
enter_fade() +
exit_fade()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment