我想更改ggplot的x轴标签。下面是我的示例代码
DF <- data.frame(seq(as.Date("2001-04-01"), to= as.Date("2001-8-31"), by="day"),
A = runif(153, 0,10))
colnames(DF)<- c("Date", "A")
ggplot(DF, aes(x = Date, y = A))+
geom_line()+
scale_x_date(date_labels = "%b", date_breaks = "month", name = "Month")
我尝试scale_x_discrete(breaks = c(0,31,60,90,120), labels = c("Jan", "Feb","Mar","Apr","May"))
失败。我知道我的数据是从4月开始的,但我想更改标签以假装从1月开始。
答案 0 :(得分:1)
您可以使用scale_x_date
,但是将日期向量传递到breaks
中,并将字符向量传递到labels
中,其长度与官方文档(https://ggplot2.tidyverse.org/reference/scale_date.html)中所述相同:
ggplot(DF,aes(x = Date, y = A, group = 1))+
geom_line()+
scale_x_date(breaks = seq(ymd("2001-04-01"),ymd("2001-08-01"), by = "month"),
labels = c("Jan","Feb","Mar","Apr","May"))
编辑:使用lubridate
或者,使用lubridate
,您可以减去3个月,然后使用此新的date变量来绘制数据:
library(lubridate)
library(dplyr)
library(ggplot2)
DF %>% mutate(Date2 = Date %m-% months(3))%>%
ggplot(aes(x = Date2, y = A))+
geom_line()+
scale_x_date(date_labels = "%b", date_breaks = "month", name = "Month")
它看起来像您想要达到的目标吗?