R ggplot2 针对计数聚合数据绘制分组箱线图的代码调整问题
解决方案
你添加weight参数后得到空白图通常由两个原因导致:一是聚合后的数据集长度列名和原代码里y = sequenceLength不匹配;二是你使用的ggplot2版本低于3.3.0,旧版本geom_boxplot不支持weight参数。以下是两种可选实现方式:
方式一:最小修改绘图代码(无需调整数据结构)
仅需修改ggplot的aes参数部分,其余所有绘图配置完全保留原有代码即可:
for_sequence_length_distribution_plot <- ggplot(for_sequence_length_distribution, aes(fill = read, group = interaction(sample, state, read), x = sample, y = length, # 若聚合后长度列仍为sequenceLength则无需修改本行 weight = count)) + # 新增权重映射 # 以下geom_boxplot、coord_flip、坐标轴设置、分面、主题等所有代码完全复用原有逻辑即可 geom_boxplot(inherit.aes = T, size = 0.25, outlier.shape = NA, alpha = .9, trim = F, width = 5 ) + coord_flip() + xlab('sample id') + ylab('sequence length [bp]') + facet_grid_paginate(facets = ~sub_id~state, ncol = 2, nrow = row_count, scales = 'free', shrink = F, byrow = T) + theme( plot.title = element_text(hjust = 0, lineheight = 0.9), plot.subtitle = element_text(hjust = 0, lineheight = 0.9), axis.title.x = element_text(margin = margin(t = 1, r = 1, b = 1, l = 1, unit = 'line')), strip.text.y = element_blank(), plot.tag.position = "bottomleft", plot.tag = element_text(hjust = 0, vjust = 0, lineheight = 0.9), plot.caption = element_text(hjust = 0, lineheight = 0, face = "italic"), plot.caption.position = "panel", legend.position = "bottom", legend.box = 'horizontal')
注意使用该方式前先将ggplot2升级到3.3.0及以上版本,避免权重参数不兼容。
方式二:零修改绘图代码,提前转换数据结构
如果不想改动已经调试好的绘图代码,只需要加一行数据预处理代码,将聚合后的计数结构还原为原始逐行观测结构:
library(tidyr) # count为你记录出现次数的列名,转换后的数据结构和你最初的逐行存储结构完全一致 for_sequence_length_distribution <- uncount(for_sequence_length_distribution, count)
转换完成后直接运行你原来的绘图代码即可,输出结果和之前完全一致。
内容的提问来源于stack exchange,提问作者pwolk
相关产品推荐
相关产品推荐

