如何在ggplot中将轴标签从数字日期更改为字符串?

时间:2018-07-16 23:40:33

标签: r ggplot2 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()

我的变量date.numeric在图中被表示为数字,其中日期数字1代表日期1/1/2015(参考日期)。如何更改y轴以“月-年”格式而不是数字格式显示日期?

enter image description here

2 个答案:

答案 0 :(得分:3)

尝试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()

reprex package(v0.2.0.9000)于2018-07-17创建。

答案 1 :(得分:0)

尝试创建日期偏移量变量并将其添加到您的y轴。

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()

该轴将类似于2015年4月,依此类推。