Reputation: 41
I’m putting together some functions to help summarize temporal data in fiscal quarters. Function I have will take a date—e.g. 2017-01-01
—and spit out factored character value that corresponds—e.g. ”1Q2017”
. I’m using my data to create graphs in ggplot. But since I factor the quarters, I can’t use attributes like geom_line()
to connect my data points, like you would for dates.
Can I create a data type for quarters that displays as quarters but behaves like dates? How would I do this?
Upvotes: 0
Views: 347
Reputation: 269654
The "yearqtr"
class in zoo represents year/quarters but acts sort of like dates in so far as internally such objects are represented numerically as year + frac where frac is 0, 1/4, 2/4, 3/4 and one can perform arithmetic on them and they format as meaningful year/quarter strings and work with lines in ggplot2 (and classic graphics and lattice graphics). See ?yearqtr
and ?scale_x_yearqtr
.
library(ggplot2)
library(zoo)
# test data
dates <- c("2017-01-01", "2017-04-01")
values <- 1:2
z <- zoo(values, as.yearqtr(dates)) # test zoo object
# 1. classic graphics
plot(z, axat = "n")
axis(1, at = time(z), labels = format(time(z), "%YQ%q"))
# 2. ggplot2 graphics
autoplot(z) + scale_x_yearqtr()
# 3. ggplot2 graphics using data frame with yearqtr
DF <- fortify.zoo(z) # test data frame
sapply(DF, class)
## Index z
## "yearqtr" "integer"
ggplot(DF, aes(Index, z)) + geom_line() + scale_x_yearqtr()
Upvotes: 1
Reputation: 6778
You just need to specify group=1
in aes
.
library(tidyverse) # install.packages('tidyverse') if needed
dat = data_frame(date = seq.Date(as.Date('2017-01-01'),
as.Date('2017-12-31'),
length.out=365),
x = rnorm(365))
dat = mutate(dat, qtr = paste0(lubridate::quarter(date), 'Q', lubridate::year(date)))
dat$qtr = as.factor(dat$qtr) # for similarity to your situation
dat %>%
group_by(qtr) %>%
summarise(n = sum(x)) %>%
ggplot(aes(x=qtr, y=n, group=1)) +
geom_line()
Upvotes: 0
Reputation: 4357
Taking the comment from @Jaap and incorporating with example graph:
library(ggplot2)
library(zoo)
df <- data.frame(date1 = c("2017-01-01", "2016-10-01", "2016-07-01"),
v1 = c(2, 4, 3))
df$date1 <- as.Date(df$date1)
ggplot(df, aes(x = date1, y = v1)) +
geom_line() +
scale_x_date(name = "quarters",
date_labels = as.yearqtr)
Upvotes: 0