You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggplot2创建双柱图:以月份为X轴,按会员类型统计计数

解决ggplot2双柱图计数问题

你的代码主要问题是没有正确指定数据列、未区分用户类别,也没处理月份的排序逻辑。以下是两种适合新手的解决方案:

方法一:让ggplot自动计数(最简单)

先把月份转换成有序因子,确保X轴按1-12的顺序排列,再用geom_bar自动统计每个月份两类用户的数量:

# 先加载ggplot2包(新手容易忘这一步)
library(ggplot2)

# 将month列转为有序因子,强制按1-12排序
df$month <- factor(df$month, levels = as.character(1:12), ordered = TRUE)

# 绘制双柱图
ggplot(df, aes(x = month, fill = member_casual)) +
  geom_bar(position = "dodge") +  # position=dodge让两类柱子并排
  scale_x_discrete(drop = FALSE) +  # 显示1-12所有月份(包括无数据的月份)
  labs(x = "月份", y = "计数", fill = "用户类型") +  # 设置标题
  theme_classic()

关键说明:

  • fill = member_casual:用颜色区分member和casual两类用户
  • geom_bar默认stat="count",会自动计算每个分组的数量,不需要手动统计
  • scale_x_discrete(drop = FALSE):避免没有数据的月份从X轴上消失,和你参考的示例图效果一致

方法二:手动汇总数据后绘图(更直观理解计数过程)

如果你想先明确看到每个月份的计数,可以用dplyr包先汇总数据,再绘图:

# 加载需要的包
library(ggplot2)
library(dplyr)

# 汇总每个月份、每个用户类型的计数
summary_df <- df %>%
  mutate(month = factor(month, levels = as.character(1:12), ordered = TRUE)) %>%
  count(month, member_casual, .drop = FALSE)  # .drop=FALSE保留所有月份

# 用汇总好的数据绘图
ggplot(summary_df, aes(x = month, y = n, fill = member_casual)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "月份", y = "计数", fill = "用户类型") +
  theme_classic()

为什么你的原代码不行?

  1. aes(x=x, y=y)是错误的,必须指定数据里的实际列名(比如x=month)
  2. 没有用fill参数区分member和casual两类用户,ggplot不知道要分柱
  3. 原代码用了stat="identity",但没有提前准备好计数数据,所以无法显示内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:22:53