#!/usr/bin/env Rscript # Usage: Rscript plot_wordcounts.R [tick_days] [input.csv] [output.svg] # By default, label every seven days, independently of the data points. library(ggplot2) args <- commandArgs(trailingOnly = TRUE) if (length(args) > 3L) { stop("Usage: Rscript plot_wordcounts.R [tick_days] [input.csv] [output.svg]") } tick_days <- if (length(args) >= 1L) { as.numeric(args[1]) } else { 7 } script_arg <- grep("^--file=", commandArgs(), value = TRUE)[1] script_dir <- dirname(normalizePath(sub("^--file=", "", script_arg))) input <- if (length(args) >= 2L) { args[2] } else { file.path(script_dir, "wordcounts.csv") } output <- if (length(args) >= 3L) { args[3] } else { file.path(script_dir, "wordcounts.svg") } counts <- read.csv(input, colClasses = "character") timezone <- Sys.getenv("TZ", unset = "Europe/Berlin") if (!nzchar(timezone)) { timezone <- "Europe/Berlin" } normalized <- sub("([+-][0-9]{2}):([0-9]{2})$", "\\1\\2", counts$date) counts$timestamp <- as.POSIXct( normalized, format = "%Y-%m-%dT%H:%M:%S%z", tz = timezone ) date_only <- grepl("^[0-9]{4}-[0-9]{2}-[0-9]{2}$", counts$date) counts$timestamp[date_only] <- as.POSIXct( counts$date[date_only], format = "%Y-%m-%d", tz = timezone ) counts$wordcount <- as.numeric(counts$wordcount) counts <- counts[order(counts$timestamp), ] # Fixed time intervals start <- as.POSIXct( format(min(counts$timestamp), "%Y-%m-%d", tz = timezone), tz = timezone ) interval <- tick_days * 86400 span <- as.numeric(difftime(max(counts$timestamp), start, units = "secs")) ticks <- start + seq(0, max(1, ceiling(span / interval))) * interval plot <- ggplot(counts, aes(x = timestamp, y = wordcount)) + scale_x_datetime( breaks = ticks, limits = range(ticks), date_labels = "%Y-%m-%d", timezone = timezone, minor_breaks = NULL ) + scale_y_continuous(labels = scales::label_comma()) + labs( title = "Thesis Word Count", x = "Date", y = "Words" ) + theme_minimal(base_size = 12) + theme( axis.text.x = element_text(angle = 45, hjust = 1), panel.grid.minor = element_blank() ) if (nrow(counts) > 1L) { plot <- plot + geom_line(linewidth = 0.5) } ggsave(output, plot, width = 10, height = 5, dpi = 180, bg = "white") message("Saved ", output)