ggplot使用scale_x_date()时<date>类未被识别的问题
解决ggplot2中scale_x_date报错的问题
问题根源
你代码里的关键错误:在aes()里把Date用factor()转成了因子类型。哪怕原数据的Date是<date>类,一旦转成因子,scale_x_date()就无法识别了——它只接受原生的Date类型对象,这就是报错transform_date() works with objects of class <Date> only的直接原因。
修复方案
把aes(factor(Date), ...)里的factor()去掉,直接用Date作为x轴映射变量,scale_x_date()就能正常工作了。
修改后的完整代码:
RA_summary_2024 |> filter(`SLF Density` != "control") |> ggplot(aes(Date, y = `Proportion Deployed`, fill = `Treatment Type`)) + # 移除factor()转换 theme_minimal() + labs(x = "Date", y = "Proportion of Population Re-Deployed") + scale_x_date(date_breaks = "1 month", date_labels = "%B") + scale_y_continuous(limits = c(-0.1, 1)) + geom_smooth(aes(group = `Treatment Type`), color = "black", method = "loess", se = TRUE) + facet_wrap(~ `Density Value`)
额外优化提示
- 若想在刻度上显示年份,可把
date_labels改成"%B %Y",会输出类似"July 2024"的格式 - 同一日期存在多组数据时,
geom_smooth()的group = Treatment Type设置能保证按分组拟合曲线,无需额外调整
内容的提问来源于stack exchange,提问作者Grace
相关产品推荐
相关产品推荐

