Reputation: 7526
I have a data set with dates plotted along the x-axis (see full dataset below):
> head(test)
date variable value
1 2018-01-17 foo 14
2 2018-01-18 foo 18
3 2018-01-19 foo 22
4 2018-01-20 foo 15
5 2018-01-21 foo 32
6 2018-01-22 foo 27
My goal is to include a second row of x-axis labels (with day of week) below the current one which shows just the date.
However, when I include an annotation in ggplot, this throws an error. Could anyone suggest a workaround?
ggplot(data=test,
aes(x=date, y=value, colour=variable)) +
geom_line() + geom_text(aes(label=value),hjust=0, vjust=0) +
annotate(geom = "text", x=date, y= -2, label = weekdays(test$date), size = 4, angle = 90)
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, :
arguments imply differing number of rows: 0, 1
Here is the sample data:
> dput(test)
structure(list(date = structure(c(17548, 17549, 17550, 17551,
17552, 17553, 17554, 17555, 17556, 17557, 17558, 17548, 17549,
17550, 17551, 17552, 17553, 17554, 17555, 17556, 17557, 17558
), class = "Date"), variable = c("foo", "foo", "foo", "foo",
"foo", "foo", "foo", "foo", "foo", "foo", "foo", "bar", "bar",
"bar", "bar", "bar", "bar", "bar", "bar", "bar", "bar", "bar"
), value = c(14L, 18L, 22L, 15L, 32L, 27L, 6L, 3L, 2L, 10L, 23L,
16L, 22L, 28L, 31L, 56L, 57L, 23L, 17L, 12L, 33L, 54L)), row.names = c(NA,
-22L), .Names = c("date", "variable", "value"), class = "data.frame")
Upvotes: 7
Views: 3611
Reputation: 43354
You can use scale_x_date
's date_labels
parameter to pass a parsing string of strptime
-style tokens, which can include literals like \n
. The breaks can be set by passing the date_breaks
parameter strings like seq.Date
.
library(ggplot2)
test <- data.frame(date = as.Date(c("2018-01-17", "2018-01-18", "2018-01-19", "2018-01-20","2018-01-21", "2018-01-22", "2018-01-23", "2018-01-24", "2018-01-25", "2018-01-26", "2018-01-27", "2018-01-17", "2018-01-18", "2018-01-19", "2018-01-20", "2018-01-21", "2018-01-22", "2018-01-23", "2018-01-24", "2018-01-25", "2018-01-26", "2018-01-27")),
variable = c("foo", "foo", "foo", "foo", "foo", "foo", "foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar", "bar", "bar", "bar", "bar", "bar", "bar", "bar"),
value = c(14L, 18L, 22L, 15L, 32L, 27L, 6L, 3L, 2L, 10L, 23L, 16L, 22L, 28L, 31L, 56L, 57L, 23L, 17L, 12L, 33L, 54L),
stringsAsFactors = FALSE)
ggplot(test, aes(date, value, colour = variable, label = value)) +
geom_line() +
geom_text(hjust = 0, vjust = 0, show.legend = FALSE) +
scale_x_date(date_breaks = 'day',
date_labels = '%b %d\n%a')
Upvotes: 11