如何用ggplot2绘制R中日期列的月份频次分组柱状图?
解决方法
你的代码报错是因为ggplot的aes()参数里不能直接用count()函数计算频数。下面提供两种可行的解决方案:
方法一:先预处理数据再绘图
先从日期列提取月份,统计各月份的出现次数,再用处理好的数据生成柱状图:
library(ggplot2) library(dplyr) # 提取月份全称并统计次数(%B替换成%b是缩写,%m是数字格式) month_counts <- bachelors %>% mutate(Month = format(Posted.On, "%B")) %>% count(Month) # 绘制柱状图 ggplot(month_counts, aes(x = Month, y = n)) + geom_bar(stat = "identity") + labs(title = "各月份发布次数统计", x = "月份", y = "出现次数")
方法二:直接在ggplot中自动统计
利用geom_bar默认的stat="count"参数,直接按月份分组并统计频数,无需提前处理数据:
library(ggplot2) ggplot(bachelors, aes(x = format(Posted.On, "%B"))) + geom_bar() + labs(title = "各月份发布次数统计", x = "月份", y = "出现次数")
可选优化:按自然月份顺序排序
如果需要让月份按1-12月的自然顺序排列(而非字母顺序),可以将月份转换为指定顺序的因子:
# 定义月份自然顺序 month_order <- c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") # 方法一中的排序处理 month_counts$Month <- factor(month_counts$Month, levels = month_order) ggplot(month_counts, aes(x = Month, y = n)) + geom_bar(stat = "identity") + labs(title = "各月份发布次数统计", x = "月份", y = "出现次数") # 方法二中的排序处理 ggplot(bachelors, aes(x = factor(format(Posted.On, "%B"), levels = month_order))) + geom_bar() + labs(title = "各月份发布次数统计", x = "月份", y = "出现次数")
内容的提问来源于stack exchange,提问作者user19375357
相关产品推荐
相关产品推荐

