Last active
July 24, 2018 12:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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