Skip to content

Instantly share code, notes, and snippets.

@jeanmanguy
Last active January 1, 2018 18:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeanmanguy/6eca222604d0eeb99fbaf3d3894e4b4b to your computer and use it in GitHub Desktop.
Save jeanmanguy/6eca222604d0eeb99fbaf3d3894e4b4b to your computer and use it in GitHub Desktop.
create a collage with the best 9 tweets from the tweet activity data
# code adapted from http://www.masalmon.eu/2017/12/30/best9of2017/
library(purrr)
library(webshot) #webshot::install_phantomjs()
library(magick)
library(dplyr)
library(glue)
# load all the CSV files in the data folder downloaded from https://analytics.twitter.com/user/<username>/tweets
my_tweets <- file.path("data", list.files("data", pattern = "^tweet_activity_metrics_")) %>% map_df(readr::read_csv)
# select the 9 best tweets
my_best_tweets <- my_tweets %>%
mutate(score = retweets + likes / 2 + replies) %>% # custom score, I don't only using the likes
arrange(desc(score)) %>%
slice(1:9)
# take screenchot of the best tweets and save them in temporary files
my_best_tweets_shots_paths <- my_best_tweets %>%
select(`Tweet id`, `Tweet permalink`) %>%
mutate(
webshot_filepath = webshot(
url = `Tweet permalink`,
file = rerun(9, tempfile(pattern = "shot_", fileext = ".png")) %>% unlist(),
cliprect = c(0, 150, 650, 650)
)
)
# collage is made column by column
# then the columns are assembled in one image
make_col <- function(path, color, geometry) {
tmp <- tempfile(fileext = ".png")
image_read(path) %>%
image_border(color = color, geometry = geometry) %>%
image_append(stack = TRUE) %>% # append pictures vertically
image_write(tmp)
return(tmp)
}
my_best_tweets_shots_paths %>%
mutate(column = rep(1:3, 3)) %>% # assign each tweet to a column
group_by(column) %>%
summarise(col_image = make_col(webshot_filepath, color = "#777777", geometry = "30x30")) %>%
pull(col_image) %>%
image_read() %>%
image_append(stack = FALSE) %>% # append column pictures horizontally
image_border(color = "#777777", geometry = "30x30") %>%
image_write("best9of2017.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment