在R中实现鱼类深度数据小时/月度分箱并绘制箱线图的技术咨询
鱼类深度数据的小时/月度分箱及箱线图绘制方案
我来帮你搞定这个箱线图的分箱问题!首先我们需要从你的日期时间列里提取出小时和月份作为分组依据,再用绘图工具生成箱线图。下面分R和Python两种常用工具来演示具体步骤:
R语言实现(基于tidyverse+ggplot2)
1. 数据预处理:提取分箱变量
首先把你的detection_time_ast转换成标准日期时间格式,然后提取小时和月份作为分组列。如果需要X轴覆盖0-25小时,我也给出了特殊分箱的示例逻辑:
# 加载必备包 library(tidyverse) # 转换日期时间格式并提取常规分箱变量 tagdataRaw2 <- tagdataRaw2 %>% mutate(detection_time_ast = ymd_hms(detection_time_ast)) %>% mutate(hour_bin = hour(detection_time_ast), # 提取带标签的月份(比如"June"),用label=FALSE可得到数字月份 month_bin = month(detection_time_ast, label = TRUE)) # 如果你确实需要0-25小时的特殊分箱(示例逻辑,可按需调整) tagdataRaw2 <- tagdataRaw2 %>% mutate(hour_bin = case_when( hour(detection_time_ast) >= 23 ~ hour(detection_time_ast) + 2, hour(detection_time_ast) == 0 ~ 24, hour(detection_time_ast) == 1 ~ 25, TRUE ~ hour(detection_time_ast) ))
2. 绘制小时分箱箱线图
按小时分组,同时区分3条鱼的深度分布:
ggplot(tagdataRaw2, aes(x = factor(hour_bin), y = sensor_value)) + geom_boxplot(aes(fill = Sp_ID)) + # 用颜色区分不同鱼类 labs(title = "鱼类深度活动按小时分箱", x = "小时", y = "深度(m)", fill = "鱼类ID") + scale_x_discrete(limits = as.character(0:25)) # 强制显示0-25的X轴刻度 theme_minimal()
3. 绘制月度分箱箱线图
按月度分组展示深度分布:
ggplot(tagdataRaw2, aes(x = month_bin, y = sensor_value)) + geom_boxplot(aes(fill = Sp_ID)) + labs(title = "鱼类深度活动按月度分箱", x = "月份", y = "深度(m)", fill = "鱼类ID") + theme_minimal()
Python语言实现(基于pandas+seaborn)
1. 数据预处理:提取分箱变量
用pandas处理日期时间,提取小时和月份:
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 转换日期时间格式 tagdataRaw2['detection_time_ast'] = pd.to_datetime(tagdataRaw2['detection_time_ast']) # 提取常规小时分箱(0-23) tagdataRaw2['hour_bin'] = tagdataRaw2['detection_time_ast'].dt.hour # 提取月份名称(如"June"),用dt.month可得到数字月份 tagdataRaw2['month_bin'] = tagdataRaw2['detection_time_ast'].dt.month_name() # 特殊0-25小时分箱逻辑(按需调整) def custom_hour_bin(hour): if hour >= 23: return hour + 2 elif hour == 0: return 24 elif hour == 1: return 25 else: return hour tagdataRaw2['hour_bin'] = tagdataRaw2['detection_time_ast'].dt.hour.apply(custom_hour_bin)
2. 绘制小时分箱箱线图
plt.figure(figsize=(12,6)) sns.boxplot(data=tagdataRaw2, x='hour_bin', y='sensor_value', hue='Sp_ID') plt.title('鱼类深度活动按小时分箱') plt.xlabel('小时') plt.ylabel('深度(m)') plt.xlim(-1, 26) # 确保X轴覆盖0-25范围 plt.xticks(range(0,26)) plt.legend(title='鱼类ID') plt.show()
3. 绘制月度分箱箱线图
plt.figure(figsize=(10,6)) # 指定月份顺序,避免乱序 month_order = ['January','February','March','April','May','June','July','August','September','October','November','December'] sns.boxplot(data=tagdataRaw2, x='month_bin', y='sensor_value', hue='Sp_ID', order=month_order) plt.title('鱼类深度活动按月度分箱') plt.xlabel('月份') plt.ylabel('深度(m)') plt.legend(title='鱼类ID') plt.show()
内容的提问来源于stack exchange,提问作者Mareike Donají Duffing Romero
相关产品推荐
相关产品推荐

