ggplot 中如何实现多行 x 轴标签

3

我想为我的图表创建一个两级x轴标签。首先在刻度附近显示月份,然后在下方显示年份。这是我的脚本:

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

它只显示标签的月份。我想在x轴下面创建另一条线,它将显示与相应月份对齐的年份。

1
你能用dput()分享一下这部分数据吗?这样任何想要帮助你的人都会更容易。 - Shibaprasadb
@Shibaprasadb 谢谢您的评论。我使用dput()函数编辑了我的帖子中的数据。 - okscientist
1个回答

3

通过更改标签格式化程序,您可以在月份下添加年份。

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


谢谢您!不过,我只想要一行中的一个标签为“2020”。您知道怎么做吗? - okscientist
@okscientist 请查看 https://dev59.com/6-k5XIcBkEYKwwoY9-t1 - tjebo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接