gpt4 book ai didi

r - 在ggplot2中用不同的日期格式化x轴

转载 作者:行者123 更新时间:2023-12-04 09:43:01 25 4
gpt4 key购买 nike

我正在努力使用 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)但这给了我一个错误。我怎样做对?

如果有任何提示,我将不胜感激!

最佳答案

您应该将 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

关于r - 在ggplot2中用不同的日期格式化x轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59773078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com