根据预先计算的汇总统计数据将离群值添加到箱线图中

问题描述 投票:0回答:1

我正在使用一个大型 (

50 x 800 000
) 稀疏矩阵 (dgCMatrix),并希望绘制箱线图以用于数据的初始检查。这是一个数字项矩阵,具有命名的行(基因)和命名的列(单元格)。我发现的最佳解决方案是通过
sparseMatrixStats::rowQuantiles()
计算相关统计数据,并将它们直接提供给箱线图几何。

我知道使用预先计算值的

geom_boxplot()
方法(这可以无缝工作!),请参阅下面的链接,但在尝试通过附加几何添加异常值时遇到问题。

https://stackoverflow.com/questions/10628847/geom-boxplot-with-precompulated-values https://stackoverflow.com/questions/65426913/how-to-make-a-boxplot-from-summary-statistics-in-ggplot2 https://stackoverflow.com/questions/68341850/group-specified-geom-boxplot-from-summary-statistics-fails-to-generate-boxplots

总而言之,我计算具有相关分位数/汇总统计数据的数据框,并将其输入

geom_boxplot()
。我还创建了一个带有异常值的(仍然相当大的)数据框,我想通过
geom_point()
geom_jitter()
将其添加到箱线图上(据我所知
geom_boxplot()
没有插槽可以将这些添加到预先计算的方法)。当尝试将异常值添加到箱线图中时,问题就出现了:

Error in `geom_point()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 2nd layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (3)
✖ Fix the following mappings: `y`
Run `rlang::last_trace()` to see where the error occurred.

这是我的问题的一个玩具示例:

genes=factor(c('a', 'b', 'c'))

# df with quantiles (simplified for brevity, with non-standard lower and upper hinges)
df <- data.frame(gene=genes, 
                 zero=c(1, 3, 0),
                 twentyfive=c(2, 4, 8),
                 fifty=c(5, 5, 12),
                 seventyfive=c(7, 9, 12),
                 hundred=c(8, 12, 15))

# Option 1 - only one outlier per gene 
df_outliers1 <- data.frame(gene=rep(genes, 1), 
                           value = sample(0:1, 3, replace = TRUE))

# Option 2 - more than one outlier per gene
df_outliers2 <- data.frame(gene=rep(genes, 1), 
                           value = c(sample(0:1, 3, replace = TRUE), sample(12:16, 3, replace=TRUE)))

# Option 1 - using df_outliers1 - works
ggplot(df, aes(x=gene, ymin=zero, lower=twentyfive, middle=fifty, upper=seventyfive, ymax=hundred)) + 
  geom_boxplot(stat='identity') + 
  geom_point(aes(y=df_outliers1$value)) + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

# Option 2 - using df_outliers2 - error (as above)!
ggplot(df, aes(x=gene, ymin=zero, lower=twentyfive, middle=fifty, upper=seventyfive, ymax=hundred)) + 
  geom_boxplot(stat='identity') + 
  geom_point(aes(y=df_outliers2$value)) + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))


奇怪的是,当每个基因只有一个离群点时(选项 1,使用

df_outliers1
),上述方法效果非常好。但一旦每个基因有更多点(选项 2,使用
df_outliers2
),就会出现错误。

解决这个问题的最佳方法是什么? (或者有没有更好的方法直接处理稀疏矩阵?)

r ggplot2 boxplot
1个回答
0
投票

请注意,图层默认继承美学。如果审美不共享,请不要在主

ggplot()
调用中指定它。另外,避免在
aes()
调用中使用“$”。将
data=
与不同的数据源一起使用。

尝试

ggplot(df, aes(x=gene)) + 
  geom_boxplot(aes(ymin=zero, lower=twentyfive, middle=fifty, upper=seventyfive, ymax=hundred), stat='identity') + 
  geom_point(aes(y=value), data=df_outliers2) + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.