You need to enable JavaScript to run this app. 如何使用ggplot基于连续值绘制双分类起止时间箱线图
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ggplot基于连续值绘制双分类起止时间箱线图

实现步骤

1. 加载依赖包

首先加载绘图和数据处理需要的工具包:

library(tidyverse)

2. 导入示例数据

你提供的示例数据可以直接通过以下代码导入到R环境中:

df <- structure(list(day = c("Mo", "Tue", "Wed", "Thur", "Fri", "Mo", "Tue", "Wed", "Thur", "Fri"), 
                     start_time1 = c(9.75, 6.5, 6.5, 6.5, 6.5, 8.5, 8.5, 8.5, 8.5, 8.75), 
                     end_time1 = c(14.75, 14.75, 8.75, 8.75, 14.75, 17.75, 17.25, 17.25, 16.5, 17.5), 
                     Pattern = c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1)), 
                class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), 
                row.names = c(NA, -10L), 
                spec = structure(list(cols = list(day = structure(list(), class = c("collector_character", "collector")), 
                                                  start_time1 = structure(list(), class = c("collector_double", "collector")), 
                                                  end_time1 = structure(list(), class = c("collector_double", "collector")), 
                                                  Pattern = structure(list(), class = c("collector_double", "collector"))), 
                                     default = structure(list(), class = c("collector_guess", "collector")), skip = 1L), class = "col_spec"))

3. 数据格式转换

ggplot需要长格式数据才能实现多分类分组绘图,因此先把原始宽数据转换为长格式,将开始时间、结束时间合并为同一列,同时新增列标记时间类型:

df_long <- df %>%
  pivot_longer(cols = c(start_time1, end_time1),
               names_to = "time_type",
               values_to = "hour") %>%
  # 将Pattern转为因子类型,方便后续分组识别
  mutate(Pattern = as.factor(Pattern),
         # 可修改时间类型的显示名称,更符合中文阅读习惯
         time_type = recode(time_type, 
                            "start_time1" = "开始时间",
                            "end_time1" = "结束时间"))

4. 绘制双分类维度箱线图

以下两种实现方式可以根据你的展示需求选择:

方式1:按时间类型分面展示

ggplot(df_long, aes(x = day, y = hour, fill = Pattern)) +
  geom_boxplot(position = position_dodge(width = 0.8), width = 0.7) +
  # 按时间类型分面,区分展示开始、结束时间的分布
  facet_wrap(~time_type) +
  labs(x = "星期", y = "时间(小时)") +
  theme_bw() +
  theme(legend.position = "top")

方式2:所有维度在x轴并列展示

ggplot(df_long, aes(x = interaction(day, time_type), y = hour, fill = Pattern)) +
  geom_boxplot(position = position_dodge(width = 0.8), width = 0.7) +
  labs(x = "星期-时间类型", y = "时间(小时)") +
  theme_bw() +
  # x轴标签旋转避免重叠
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 15:24:03