在函数中并排绘制箱形图和密度图

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

我想使用箱形图和密度图比较标记组之间的数据。我为此做了一个函数,让我们更容易输入我需要的数据和我想使用的特征,以及两组的标签是什么(

y
将是一个二进制特征):

density_and_boxplot = function(data = data, metadata = metadata, cell.type = 'cell.type', y = c()) {

  combination = merge(data, metadata, by=0, all=TRUE) %>% na.omit()
  p1 = ggplot(data = combination, aes(x= cell.type, fill=as.factor(y))) + geom_boxplot() + coord_flip() + title(paste('Box plot of',cell.type))
  p2 = ggplot(data = combination, aes(x= cell.type, fill=as.factor(y))) + geom_density(alpha=.5) + title(paste('Distribtuion of',cell.type))
 
  return(cowplot::plot_grid(p1,p2))
}

调用函数:

density_and_boxplot(data = scores, metadata = mydata, cell.type = 'B-cells', y = 'PD')

我得到空图,为什么会这样?

r ggplot2 boxplot
1个回答
0
投票

将您的

cell.type
变量传递给
x = cell.type
调用中的
aes()
行会导致一个带有
aes(x = "B-cells")
NOT
aes(x = B-cells)
的图,正如您可能希望的那样 - 即它传递字符串而不是选择数据集中的现有变量.

相反,使用:

x = .data[[cell.type]]

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