简体   繁体   English

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

[英]How to manually change the x-axis label in ggplot?

I want to change the x-axis labels of my ggplot.我想更改 ggplot 的 x 轴标签。 Below is my sample code下面是我的示例代码

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

I tried scale_x_discrete(breaks = c(0,31,60,90,120), labels = c("Jan", "Feb","Mar","Apr","May")) with no success.我试过scale_x_discrete(breaks = c(0,31,60,90,120), labels = c("Jan", "Feb","Mar","Apr","May"))没有成功。 I know my data is from April but would like to change the labels pretending that its from January.我知道我的数据是从 4 月开始的,但我想更改标签,假装是从 1 月开始。

You can use scale_x_date but pass a vector of date into breaks and a character vector in labels of the same length as described in the official documentation ( https://ggplot2.tidyverse.org/reference/scale_date.html ):您可以使用scale_x_date但将日期向量传递到与官方文档( https://ggplot2.tidyverse.org/reference/scale_date.html )中描述的长度相同的labels中的breaks和字符向量中:

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

在此处输入图片说明

EDIT: Substract months using lubridate编辑:使用lubridate

Alternatively, using lubridate , you can substract 3 months and use this new date variable to plot your data:或者,使用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")

在此处输入图片说明

Does it look what you are trying to achieve ?它看起来像你想要达到的目标吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM