3

I want to create a two-level x-axis label for my plot. First showing months near the ticks and the year below. Here is my script:

Date <- c(2020-09-07,2020-09-14,2020-09-21,2020-09-28,2020-10-07,2020-10-14,2020-10-21,2020-10-28,2020-11-07,2020-11-14,2020-11-21,2020-1-28)
A <- c(28.2,28.4,28.6,28.8,28,28.5,27.6,27.9,27.9,28.1,28.4,29)

test<-data.frame(Date,A)

test$Date <- as.Date(test$Date, origin = "2020-09-07")

ggplot(test, aes(x=Date, y=A))+
  geom_line(na.rm=TRUE)+
  xlab("") + ylab("A")+
  (scale_x_date(breaks=date_breaks("1 month"),labels=date_format("%b")))+
  scale_y_continuous(expand = c(0, 0), limits = c(26, 31))+
  theme_bw()

It only shows the months for the labels. I would like to create another line below the x-axis where it would show the year that lines up with the corresponding months.

1 Answers1

3

You can add the year below the month by changing the label formatter

ggplot(test, aes(x=Date, y=A))+
  geom_line(na.rm=TRUE)+
  xlab("") + ylab("A")+
  (scale_x_date(breaks=scales::date_breaks("1 month"),labels=scales::date_format("%b\n%Y")))+
  scale_y_continuous(expand = c(0, 0), limits = c(28, 31))+
  geom_point(shape=1)+
  theme_bw()

year under month name

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thank you for this! However, I would like only one label of "2020" for the whole row. Would you know how to do this? – okscientist Oct 12 '21 at 07:35
  • @okscientist check https://stackoverflow.com/questions/44616530/axis-labels-on-two-lines-with-nested-x-variables-year-below-months – tjebo Oct 12 '21 at 11:55