使用ggplot2在不同日期下对x轴进行格式化

3

我正在努力使用ggplot2格式化堆积面积图的x轴。这是我的数据:

df <- data.frame(
     Taxon = c("Others", "Dinos", "Diatoms", "Others", "Dinos", "Diatoms", "Others", "Dinos", "Diatoms", "Others", "Dinos", "Diatoms", "Others", "Dinos", "Diatoms", "Others", "Dinos", "Diatoms", "Others", "Dinos", "Diatoms", "Others", "Dinos", "Diatoms"),
     Abundance = c(14192, 120, 440, 6000, 80, 360, 25800, 4384, 169428, 879103, 2000, 52360, 213508, 22560, 470900, 472808, 11920, 316312, 81504, 6280, 15096, 50656, 11360, 43448),
     Date = c("05/01/2019", "05/01/2019", "05/01/2019", "09/03/2019", "09/03/2019", "09/03/2019", "11/04/2019", "11/04/2019", "11/04/2019", "01/05/2019", "01/05/2019", "01/05/2019", "01/06/2019", "01/06/2019", "01/06/2019", "01/07/2019", "01/07/2019", "01/07/2019", "01/08/2019", "01/08/2019", "01/08/2019", "01/09/2019","01/09/2019", "01/09/2019")
)

df %>% group_by(Date, Taxon) %>% summarise_all(sum) -> df1

ggplot(df1, aes(x=as.Date(Date, format="%d/%m/%Y"), Abundance, colour=Taxon, fill=Taxon)) + geom_area(stat="identity", position="stack") + labs(x = "", y = "") + scale_x_date(labels = date_format("%d/%m/%Y")) + theme(axis.text.x = element_text(angle = 45, vjust = 0.5))

这给我展示了以下的图表:

ggplot2

我的问题如下:

  1. 如何使x轴标签对应df2$Date中的日期而不是每个月的第一天?
  2. 我希望所有日期都在x轴上可见。我尝试使用scale_x_continuous(labels=dates)dates <- unique(df1$Date),但这给我一个错误。如何解决它?

非常感谢任何提示!


如果您想调整断点(即显示标签的值),请使用 date_breaks 参数,而不是 date_labels 参数。 - camille
这个回答解决了你的问题吗?R:ggplot在x轴上显示所有日期 - Cole Robertson
谢谢你的帮助!Jonathan提供了我所需要的。 - wylierose
3个回答

1

使用breaks参数

要更改日期频率,您需要在scale_x_date()函数上使用breaks参数,如下所示:

+ scale_x_date(labels = date_format("%d/%m/%Y"), breaks = date_breaks("2 weeks"))

这是一个包含 两周 休息的完整图形代码:

library(dplyr)
library(ggplot2)
library(scales)

df1 %>% ggplot(aes(
  x = as.Date(Date, format = "%d/%m/%Y"),
  Abundance,
  colour = Taxon,
  fill = Taxon
)) +
  geom_area(stat = "identity", position = "stack") +
  labs(x = "", y = "") +
  scale_x_date(labels = date_format("%d/%m/%Y"), breaks = date_breaks("2 weeks")) +
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5))

enter image description here

希望这有所帮助。

谢谢你的帮助,但是Jonathan的回答正是我所需要的。 - wylierose

1
你应该将 scale_x_date 中的 breaks 参数设置为与你分配给 labels 的相同对象。
scale_x_date(labels = as.Date(df1$Date, format="%d/%m/%Y"), 
breaks = as.Date(df1$Date, format="%d/%m/%Y"))

Plot


这正是我想要的!非常感谢你! - wylierose

0
调整scale_x_date中的date_breaks参数,例如:
ggplot(df1, aes(x=as.Date(Date, format="%d/%m/%Y"), Abundance, colour=Taxon, fill=Taxon)) + 
  geom_area(stat="identity", position="stack") + labs(x = "", y = "") + 
  scale_x_date(labels = date_format("%d/%m/%Y"),date_breaks = '1 week') + 
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5))

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