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

基于给定R数据框绘制两组并排分组条形图求助

复现目标条形图的R实现方法

步骤1:数据预处理

原数据框的数值列均为字符类型,需转换为可计算的数值格式,同时修正数据中的小疏漏(如Biv_E_activity里的"60"补全为"60%"):

# 转换数据类型
df.new$Correlation_task_persistence <- as.numeric(df.new$Correlation_task_persistence)
df.new$Biv_A_task_persistence <- as.numeric(sub("%", "", df.new$Biv_A_task_persistence))
df.new$Biv_E_task_persistence <- as.numeric(sub("%", "", df.new$Biv_E_task_persistence))
df.new$Correlation_activity <- as.numeric(df.new$Correlation_activity)
df.new$Biv_A_activity <- as.numeric(sub("%", "", df.new$Biv_A_activity))
df.new$Biv_E_activity <- as.numeric(sub("%", "", ifelse(df.new$Biv_E_activity == "60", "60%", df.new$Biv_E_activity)))
# 设置年龄显示顺序,与目标图对齐
df.new$age <- factor(df.new$age, levels = c("12", "18", "24", "30"))

步骤2:转换为长数据格式

ggplot更适配长数据结构,使用tidyr和dplyr完成格式转换:

library(tidyr)
library(dplyr)

df_long <- df.new %>%
  pivot_longer(
    cols = -age, 
    names_to = c("metric", "domain"), 
    names_sep = "_",
    values_to = "value"
  ) %>%
  # 修正拆分后的分类名称,匹配原数据逻辑
  mutate(domain = ifelse(domain == "task", "task_persistence", domain))

步骤3:绘制分组条形图

用ggplot2实现分面板的分组条形图,还原目标图的核心样式:

library(ggplot2)

ggplot(df_long, aes(x = age, y = value, fill = metric)) +
  # 绘制分组条形,调整间距避免重叠
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  # 按领域分面板,y轴自由缩放适配不同数值范围
  facet_wrap(~domain, scales = "free_y") +
  # 设置坐标轴与图例标题
  labs(x = "年龄", y = "数值", fill = "指标类型") +
  # 匹配目标图的灰色系填充色
  scale_fill_manual(values = c("Correlation" = "#636363", "Biv_A" = "#bdbdbd", "Biv_E" = "#f0f0f0")) +
  # 使用简洁主题,去除冗余网格线
  theme_bw() +
  theme(
    panel.grid = element_blank(),
    axis.text = element_text(size = 10),
    axis.title = element_text(size = 12),
    legend.title = element_text(size = 12),
    strip.text = element_text(size = 12)
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:35:33