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

在R中按十年范围分组统计出生年份数据并绘图

按十年分组统计出生年份并可视化

1. 转换数据类型

原数据的years列是字符格式,先转为数值型才能进行区间分组操作:

birth_year$years <- as.numeric(birth_year$years)

2. 按十年区间分组并统计计数

方法1:Base R 实现

# 定义分组区间(1920到2000,每10年为一组)
breaks <- seq(1920, 2000, by = 10)
# 生成指定格式的分组标签
labels <- paste0("(", breaks[-length(breaks)], "-", breaks[-1], "]:")
# 对出生年份进行分组
birth_year$group <- cut(birth_year$years, breaks = breaks, labels = labels, right = TRUE)
# 统计每组人数并转为数据框
group_counts <- as.data.frame(table(birth_year$group))
# 重命名列名匹配需求格式
colnames(group_counts) <- c("birth_year", "count")

# 查看结果
print(group_counts)

方法2:dplyr 简洁实现

如果习惯使用tidyverse工具链:

library(dplyr)

group_counts <- birth_year %>%
  mutate(years = as.numeric(years)) %>%
  mutate(
    birth_year = cut(
      years,
      breaks = seq(1920, 2000, 10),
      labels = paste0("(", seq(1920, 1990, 10), "-", seq(1930, 2000, 10), "]:")
    )
  ) %>%
  count(birth_year, name = "count")

# 查看结果
print(group_counts)

两种方法都会输出你需要的分组统计格式:

birth_year count
1 (1920-1930]:     5
2 (1931-1940]:     8
3 (1941-1950]:     4
4 (1951-1960]:     3
5 (1961-1970]:     5
6 (1971-1980]:     5
7 (1981-1990]:     5
8 (1991-2000]:     9

3. 基于分组数据绘制图表

用ggplot2绘制柱状图:

library(ggplot2)

ggplot(group_counts, aes(x = birth_year, y = count)) +
  geom_bar(stat = "identity", fill = "#4285F4") +
  labs(title = "出生年份十年分组统计", x = "出生年份区间", y = "人数") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:55:15