You need to enable JavaScript to run this app. 如何在R ggplot2中按年月分组绘制柱状图,避免按日生成过多柱子
优惠活动
大模型
产品
解决方案
定价
更多

如何在R ggplot2中按年月分组绘制柱状图,避免按日生成过多柱子

问题描述

我现有一段代码,使用N.Content列作为y轴、Collection.date列作为x轴绘图,功能可正常运行,但我无法实现按年月分组生成柱子的需求,当前代码是按年月日逐天绘制,最终生成了约600个柱子,远多于预期的19个。以下是我的代码:

#Format the Collection Date as a date and not a character format
df_var$Collection.date = as.Date(df_var$Collection.date, format = "%Y-%m-%d")
str(df_var)

##====================================================================================================

## Make a plot taking our variant_df with x axis being the Collection,date, and the y axis being the N Content, then fill the color by Clade

variant_plots = ggplot(df_var, aes(x= as.Date(`Collection.date`, format = "%Y-%m"), y= `N.Content`, fill = Clade)) +
  geom_bar(stat='identity', position = "fill") +
  
  ##Limit the y axis from 0 to 1
ylim(0.0, 1)+
  
 # scale_y_continuous(labels = scales::percent, limits=c(0,1))
  
  #scale_x_date Supposed to limit from Jan 2020 - July 2021

  scale_x_date(date_labels = "%m-%Y" , limits = as.Date(c('2020-01-01','2021-07-01'))) 

##Print our plot
variant_plots

代码运行结果如下:
实际输出绘图
我需要的坐标轴效果如下:
预期输出绘图
可见当前绘图按天生成柱子,数量是预期的百倍左右。请问如何修改我的代码,使x轴按年月分组展示,最终得到符合预期的柱状图?


解决方案

你当前的问题核心是:as.Date(Collection.date, format = "%Y-%m")写法无效,因为format参数仅用于将字符类型转换为日期类型时指定解析格式,你已经提前把Collection.date转为日期类型了,这一步不会去掉日期中的「日」信息,ggplot还是会把每一天当做独立的x轴分组。

可以通过「将所有日期统一归到对应月份的第一天」的方式实现按年月分组,修改方案如下:

  1. 先加载lubridate包(专门处理日期的常用工具包,没有的话先执行install.packages("lubridate")安装)
  2. 修改x轴映射逻辑,同时给x轴设置每月一个的刻度

修改后的完整代码:

library(lubridate)
library(ggplot2)

# 原有日期格式化逻辑不变
df_var$Collection.date = as.Date(df_var$Collection.date, format = "%Y-%m-%d")

variant_plots = ggplot(df_var, aes(
  # 将所有日期对齐到当月第一天,同一个月的所有数据会归到同一个x值
  x = floor_date(Collection.date, unit = "month"), 
  y = `N.Content`, 
  fill = Clade
)) +
  geom_bar(stat='identity', position = "fill") +
  ylim(0.0, 1) +
  # 增加date_breaks参数,指定每月显示一个刻度标签
  scale_x_date(
    date_labels = "%m-%Y", 
    limits = as.Date(c('2020-01-01','2021-07-01')),
    date_breaks = "1 month"
  ) 

variant_plots

如果不想额外安装lubridate包,也可以用base R的方法把日期转为年月因子,只需要把x轴映射改成x = factor(format(Collection.date, "%Y-%m"))即可,不过这种方式需要注意因子顺序是否和日期顺序一致,更推荐用floor_date的方案。


内容的提问来源于stack exchange,提问作者ghoolie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:27:05