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

使用ggplot复刻FiveThirtyEight Bechdel图表:年份分组问题求助

嘿,我来帮你搞定这个年份分组的问题,顺便复刻出FiveThirtyEight那篇文章里的第一个图表!你现在的问题是用了连续的year做直方图,但原图表是按十年分组的堆叠百分比柱状图,所以我们需要先处理数据,再调整ggplot的图层:

第一步:给数据加年份分组

首先得把连续的年份转换成十年一组的离散变量,比如1970s、1980s这种。用dplyr来处理很方便:

library(dplyr)
library(ggplot2)
library(ggthemes) # 用来匹配FiveThirtyEight的风格

# 加载数据集
bechdel <- fivethirtyeight::bechdel

# 清理数据+创建十年分组
bechdel_clean <- bechdel %>%
  filter(!is.na(clean_test)) %>% # 删掉测试结果缺失的行
  mutate(
    decade = case_when(
      year %in% 1970:1979 ~ "1970s",
      year %in% 1980:1989 ~ "1980s",
      year %in% 1990:1999 ~ "1990s",
      year %in% 2000:2009 ~ "2000s",
      year %in% 2010:2019 ~ "2010s"
    )
  ) %>%
  filter(!is.na(decade)) # 过滤掉不在分组里的年份

第二步:绘制复刻图表

原文章的第一个图是堆叠的百分比柱状图,每个十年里展示不同Bechdel测试结果的占比。用geom_bar配合position="fill"就能实现百分比堆叠,再加上FiveThirtyEight的主题:

ggplot(bechdel_clean, aes(x = decade, fill = clean_test)) +
  # 堆叠柱状图,position="fill"自动转成百分比,白色边框区分类别
  geom_bar(position = "fill", color = "white", size = 0.3) +
  # y轴显示百分比
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
  # 匹配原文章的颜色和标签(你可以根据原图微调颜色)
  scale_fill_manual(
    values = c("pass" = "#1a9850", "dubious" = "#fee08b", "men" = "#fc8d59", "notalk" = "#d73027"),
    labels = c(
      "pass" = "Passes Test",
      "dubious" = "Dubious Pass",
      "men" = "Women only talk about men",
      "notalk" = "Women don't talk to each other"
    )
  ) +
  # 标题和标签尽量贴近原文章
  labs(
    title = "The Dollar-And-Cents Case Against Hollywood's Exclusion Of Women",
    subtitle = "Percentage of films passing the Bechdel test, by decade",
    x = "Decade",
    y = "Percentage of Films",
    fill = "Bechdel Test Result"
  ) +
  # 套用FiveThirtyEight的主题风格
  theme_fivethirtyeight() +
  # 微调细节,让图表更美观
  theme(
    plot.title = element_text(size = 14, face = "bold"),
    plot.subtitle = element_text(size = 12),
    legend.position = "bottom",
    legend.title = element_text(face = "bold")
  )

为啥你的原代码不行?

你之前用的是geom_histogram,这是用来展示连续变量(比如年份)的分布的,但原图表是把年份分成离散的组,然后展示每个组内的类别占比,所以换成geom_bar+分组后的decade变量才是正确的方向。position="fill"这个参数是关键,它会把每个十年里的计数转换成百分比,和原文章的效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:54:48