Skip to content

Instantly share code, notes, and snippets.

@mmparker
Created October 4, 2016 22:06
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 mmparker/486d8f07a7920b3d0f630bf6ec3f7adb to your computer and use it in GitHub Desktop.
Save mmparker/486d8f07a7920b3d0f630bf6ec3f7adb to your computer and use it in GitHub Desktop.
An attempt to put date labels on an integer-sequenced x-axis, when there are multiple sequential points per date.
# Always
options(stringsAsFactors = FALSE)
library(tidyverse)
# Setting the ggplot2 theme
theme_set(theme_bw())
# How many periods of data to generate?
n_quarters <- 10
# Which metrics?
metrics <- c("Gained", "Lost", "Exploded")
n_metrics <- length(metrics)
# Calculate the offsets for each metric to ensure even spacing in the plot
metric_offset <- seq(from = 0, by = 1 / n_metrics, length.out = n_metrics)
# Create a sequence of dates
dates <- seq.Date(Sys.Date(), by = "1 day", length.out = n_quarters)
# Generate the data
testdat <- expand.grid(date = dates, metric = metrics) %>%
as.data.frame() %>%
arrange(date) %>%
# Convert dates into integers, then add the offset so each metric has a
# unique spot on the x-axis
mutate(x = as.integer(date) + metric_offset,
y = x + rnorm(n()))
# Check the results
testdat
# Plot on the numeric x-axis, but convert to Dates for labeling
# The breaks = ... nonsense is required to ensure that the breaks fall on whole
# integers.
ggplot(testdat, aes(x = x, y = y, color = metric)) +
geom_point(size = 4) +
scale_x_continuous(breaks = function(x) { seq(from = floor(x[1]),
to = ceiling(x[2]),
by = 1) },
labels = function(x) { as.Date(x, origin = "1970-01-01") })
# Here's how I'd go about getting Year-Quarter formatting on x.
# I hadn't thought it through, but you might have to change by = 1 to
# by = 90 or something if the dates are ~90 days apart... ugh.
format_yr_qtr <- function(x) {
x_Date <- as.Date(x, origin = "1970-01-01")
paste(format(x_Date, "%Y"), quarters(x_Date))
}
ggplot(testdat, aes(x = x, y = y, color = metric)) +
geom_point(size = 4) +
scale_x_continuous(breaks = function(x) { seq(from = floor(x[1]),
to = ceiling(x[2]),
by = 1) },
labels = format_yr_qtr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment