Sergio Nolazco
Sergio Nolazco

Reputation: 179

How to change axis labels from numeric dates to string in ggplot?

I have this simple example of a boxplot:

date.numeric <- c(98,105,110,120,75,35,200,167,365,425,400,398)
age.class <- c("juv","juv","juv","juv","juv","ad","ad","ad","ad","ad","ad","ad")
mytable <- data.frame(date.numeric,age.class)
ggplot(mytable, aes(x=age.class, y=date.numeric)) +
  geom_boxplot()

My variable date.numeric is depicted as numbers in the plot, in which date number 1 represents date 1/1/2015 (reference date). How can I change the y-axis to show dates in format "month-year" instead of the numeric format?

enter image description here

Upvotes: 2

Views: 1335

Answers (2)

The Lyrist
The Lyrist

Reputation: 444

try creating a date offset variable and add that to your y-axis.

date.start <- as.Date('2015-01-01')
date.numeric <- c(98,105,110,120,75,35,200,167,365,425,400,398)
age.class <- c("juv","juv","juv","juv","juv","ad","ad","ad","ad","ad","ad","ad")
mytable <- data.frame(date.numeric,age.class)
ggplot(mytable, aes(x=age.class, y=date.numeric+date.start)) + geom_boxplot()

The axis would then look like Apr 2015, etc.

Upvotes: 0

TC Zhang
TC Zhang

Reputation: 2797

try as.Date()

library(ggplot2)
date.numeric <- c(98,105,110,120,75,35,200,167,365,425,400,398)
age.class <- c("juv","juv","juv","juv","juv","ad","ad","ad","ad","ad","ad","ad")
mytable <- data.frame(date.numeric,age.class)

mytable$date <- (as.Date(date.numeric,origin = "2015/1/1"))
ggplot(mytable, aes(x=age.class, y=date)) +
  geom_boxplot()

Created on 2018-07-17 by the reprex package (v0.2.0.9000).

Upvotes: 4

Related Questions