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

如何用R的ggforce绘制W.E.B.杜波伊斯风格45度倾斜堆叠条形图

绘制W.E.B.杜波伊斯风格45度倾斜堆叠条形图

需求说明

基于给定数据,在R中复刻W.E.B.杜波伊斯标志性的45度倾斜堆叠条形图样式。

给定数据

df <- structure(list(
  Category = c("Government", "Society", "Persons", "Property", "Miscellaneous"),
  Percent = c(0.7, 13.4, 27.6, 48.2, 10.6)
), class = "data.frame", row.names = c(NA, -5L))

完整实现代码

结合你的思路,以下是贴合杜波伊斯风格的优化实现:

library(ggplot2)
library(dplyr)
library(tidyr)

# 原始数据
df <- structure(list(
  Category = c("Government", "Society", "Persons", "Property", "Miscellaneous"),
  Percent = c(0.7, 13.4, 27.6, 48.2, 10.6)
), class = "data.frame", row.names = c(NA, -5L))

# 反转数据顺序并锁定因子水平,保证堆叠顺序符合杜波伊斯风格
df_rev <- df %>%
  arrange(desc(Category)) %>%
  mutate(Category = factor(Category, levels = Category))

# 计算每个堆叠块的上下边界
df_rev <- df_rev %>%
  mutate(
    cum_pct = cumsum(Percent),
    y_start = lag(cum_pct, default = 0),
    y_end = cum_pct
  )

# 定义45度顺时针旋转矩阵
angle <- -pi/4
rotate_matrix <- matrix(c(cos(angle), -sin(angle), sin(angle), cos(angle)), ncol = 2, byrow = TRUE)

# 生成每个堆叠块的旋转顶点
bar_width <- 30
df_poly <- df_rev %>%
  rowwise() %>%
  mutate(
    # 原始矩形的四个顶点
    points = list(
      c(0, y_start), c(0, y_end), 
      c(bar_width, y_end), c(bar_width, y_start)
    ),
    # 对每个顶点应用旋转
    rotated = list(lapply(points, function(p) rotate_matrix %*% p))
  ) %>%
  unnest(rotated) %>%
  mutate(
    x = rotated[[1]],
    y = rotated[[2]]
  ) %>%
  select(-points, -rotated)

# 杜波伊斯风格暖色调配色
dubois_colors <- c("#802E2E", "#A14F3D", "#B86F4A", "#D3976A", "#E5C2A0")

# 绘制图表
ggplot(df_poly, aes(x = x, y = y, group = Category, fill = Category)) +
  geom_polygon(linewidth = 0.5, color = "black") + # 黑色边框贴合原版风格
  # 添加倾斜的百分比标签
  geom_text(
    data = df_rev,
    aes(
      x = (rotate_matrix %*% c(bar_width/2, (y_start + y_end)/2))[1],
      y = (rotate_matrix %*% c(bar_width/2, (y_start + y_end)/2))[2],
      label = paste0(Percent, "%")
    ),
    color = "white",
    fontface = "bold",
    angle = 45
  ) +
  scale_fill_manual(values = dubois_colors) +
  theme_void() +
  theme(
    legend.position = "right",
    legend.title = element_text(face = "bold")
  ) +
  labs(fill = "Category")

核心优化点

  • 堆叠顺序校正:反转数据并锁定因子水平,确保堆叠层级与杜波伊斯原版图表一致
  • 旋转逻辑简化:统一处理顶点旋转,避免重复代码,保证每个堆叠块形状准确
  • 风格细节适配:使用暖色调配色、黑色边框、倾斜标签,还原杜波伊斯图表的视觉特征
  • 标签定位精准:基于堆叠块中心坐标旋转后计算标签位置,保证标签居中显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:37:52