如何在ggplot中手动更改x轴标签?

问题描述 投票:1回答:1

我想更改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月。

r date ggplot2 label axis-labels
1个回答
0
投票

您可以使用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"))

enter image description here

EDIT:使用lubridate]减去月份

或者,使用lubridate,您可以减去3个月,并使用此新的日期变量来绘制数据:

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

enter image description here

看起来像您想要达到的目标吗?

© www.soinside.com 2019 - 2024. All rights reserved.