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

如何使用ggplot复现base R绘制的箱线图并按性别分组展示

解决方案

ggplot要求输入长格式数据,你需要先将当前的宽格式数据集做转换,再通过分组偏移参数实现同指标下男女箱线图并排展示,完整可运行代码如下:

# 未安装依赖包先运行:install.packages("tidyverse")
library(tidyverse)

# 构造示例数据集
Gender <- c("Man", "Man", "Woman", "Woman", "Man", "Woman", "Woman", "Man", "Woman", "Man")
V1 <- c(85, 100, 80, 70, 85, 85, 80, 70, 100, 80)
V2 <- c(92, 92, 84, 78, 80, 94, 100, 94, 100, 94)
V3 <- c(86, 80, 60, 53, 80, 73, 80, 73, 86, 93)
V4 <- c(80, 70, 20, 40, 60, 20, 100, 40, 60, 20)
V5 <- c(100, 90, 100, 80, 100, 100, 100, 100, 100, 100)
Dados <- data.frame(Gender, V1, V2, V3, V4, V5)

# 宽格式转长格式,适配ggplot语法
Dados_long <- Dados %>%
  pivot_longer(
    cols = -Gender,
    names_to = "Indicator",
    values_to = "Score"
  ) %>%
  mutate(Indicator = factor(Indicator,
                            levels = c("V1", "V2", "V3", "V4", "V5"),
                            labels = c("Sexismo", "LGBTfobia", "AmbUniver", "GenSexEns", "Valores")))

# 绘制分性别并排箱线图(按性别区分填充色版本)
ggplot(Dados_long, aes(x = Indicator, y = Score, fill = Gender)) +
  geom_boxplot(
    position = position_dodge(width = 0.8),
    lwd = 1.2
  ) +
  scale_y_continuous(limits = c(0, 100)) +
  labs(x = NULL, y = NULL) +
  theme_classic() +
  theme(
    axis.text = element_text(size = 14),
    legend.text = element_text(size = 12),
    legend.title = element_text(size = 13),
    panel.border = element_rect(fill = NA, linewidth = 1)
  )

# 若要保留原base图按指标区分填充色的风格,可替换为以下绘图代码,用边框颜色区分性别:
# ggplot(Dados_long, aes(x = Indicator, y = Score, color = Gender)) +
#   geom_boxplot(aes(fill = Indicator), position = position_dodge(width = 0.8), lwd = 1.2) +
#   scale_fill_manual(values = c("darkred", "darkolivegreen4", "yellow3", "purple4", "darkorange3")) +
#   scale_y_continuous(limits = c(0, 100)) +
#   labs(x = NULL, y = NULL) +
#   theme_classic() +
#   theme(
#     axis.text = element_text(size = 14),
#     legend.text = element_text(size = 12),
#     legend.title = element_text(size = 13),
#     panel.border = element_rect(fill = NA, linewidth = 1)
#   )

核心实现说明

  • 宽转长处理后,所有指标的得分统一映射到y轴,指标名映射到x轴,即可实现V1-V5在x轴排列的效果
  • position_dodge()参数控制同分组下箱线图的横向偏移,是实现男女箱线图并排的核心配置
  • 可根据视觉需求自行调整颜色映射规则、字体大小、边框样式等参数,匹配你的调研绘图规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:36:04