基于R ggplot2绘制分时间点时间序列雨云图问题求助
解决方案
你现有代码的核心问题是图层x轴映射混乱:geom_point层自定义的x = as.numeric(ID)-.15和全局的x=Time冲突,导致所有时间维度的数据被强制聚合展示,无法按时间拆分。
另外你示例数据中Time共有1000个取值,如果直接为每个时间点生成独立子图会过于拥挤,建议先按需做时间分箱,或者筛选目标时间点后再绘图。
以下提供两种常用实现方案:
方案1:同画布按时间分组展示(每个时间点下排列4个ID的雨云图)
核心逻辑是将x映射为Time,同时用interaction(Time, ID)设置分组,调整各图层的位置偏移,让每个时间点下的4组ID数据并排展示:
source("https://gist.githubusercontent.com/benmarwick/2a1bb0133ff568cbe28d/raw/fb53bd97121f7f9ce947837ef1a4c65a73bffb3f/geom_flat_violin.R") library(ggplot2) set.seed(123) ID = rep(c("BAU","IMP","SGR","CR"), each=5000) Time = rep (c(1:1000), each = 20) data <- data.frame( ID, Time, profits = runif(20000,0,1)) # 这里为了演示方便,先筛选前10个时间点,你可以按需替换为自己需要的时间范围 data_filter <- subset(data, Time %in% 1:10) ggplot(data_filter, aes(x = as.factor(Time), y = profits, fill = ID, group = interaction(Time, ID))) + # 扁平小提琴图(雨云的云部分),偏移量对应ID的排序 geom_flat_violin(position = position_nudge(x = 0.2 + as.numeric(as.factor(ID))*0.15, y = 0), adjust = 1.5, trim = FALSE, alpha = 0.5, colour = NA) + # 散点(雨部分),位置对应同组的小提琴图 geom_point(aes(x = as.numeric(as.factor(Time)) + as.numeric(as.factor(ID))*0.15 - 0.22, colour = ID), position = position_jitter(width = 0.03), size = 0.8, shape = 20, alpha = 0.6) + # 箱线图,位置对齐同组数据 geom_boxplot(width = 0.1, outlier.shape = NA, alpha = 0.5, colour = "black", position = position_dodge(width = 0.15)) + scale_colour_brewer(palette = "Dark2") + scale_fill_brewer(palette = "Dark2") + labs(x = "时间点", y = "收益", title = "各时间点分组雨云图") + theme_classic() + theme(legend.position="top")
方案2:每个时间点生成独立子图(分面实现)
如果需要每个时间点单独成图,使用facet_wrap按Time分面即可,同样建议先筛选少量时间点演示:
# 筛选前6个时间点做分面演示 data_filter <- subset(data, Time %in% 1:6) ggplot(data_filter, aes(x = ID, y = profits, fill = ID)) + geom_flat_violin(position = position_nudge(x = 0.1, y = 0), adjust = 1.5, trim = FALSE, alpha = 0.5, colour = NA) + geom_point(aes(x = as.numeric(ID)-0.15, colour = ID), position = position_jitter(width = 0.05), size = 0.8, shape = 20, alpha = 0.6) + geom_boxplot(width = 0.1, outlier.shape = NA, alpha = 0.5, colour = "black") + scale_colour_brewer(palette = "Dark2") + scale_fill_brewer(palette = "Dark2") + facet_wrap(~Time, nrow = 2, labeller = labeller(Time = ~paste0("时间点", .x))) + labs(y = "收益", title = "各时间点独立雨云图") + theme_classic() + theme(legend.position="top", axis.title.x = element_blank())
内容的提问来源于stack exchange,提问作者Sadaf
相关产品推荐
相关产品推荐

