如何手动更改ggplot中的x轴标签?
How to manually change the x-axis label in ggplot?
我想更改 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 月。
您可以使用 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 个月并使用这个新的日期变量来绘制您的数据:
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")
它看起来像你想要达到的目标吗?
我想更改 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 月。
您可以使用 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 个月并使用这个新的日期变量来绘制您的数据:
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")
它看起来像你想要达到的目标吗?