首页 > 解决方案 > ggplot2 在同一个图块中绘制组变量的所有级别

问题描述

我想为每个基因绘制“x”的每个值,以及它所属的三个非排他“类型”(组变量)的每个级别。是否可以将正方形或平铺拆分为组变量的三个级别,或者将每个级别彼此相邻显示,而不是如下所示的不同方面?

例如,如果它是另一个图,我可以使用“对”并抖动组变量。

library(ggplot2)
dat <- data.frame(gene = factor(c(rep('gene1',2), rep('gene2',2), rep('gene2',2), 
rep('gene3',2), rep('gene3',2), rep('gene1',2))),
            x = factor(c(rep('a',3), rep('a',3), rep('b',3), rep('c',3))))
dat$type <- factor(rep(1:3))

library(ggplot2)
ggplot(dat, aes(gene, x, fill=type)) + geom_tile() + facet_grid(type ~ .)

标签: rggplot2tile

解决方案


我是否理解正确你想要这个:

    library(ggplot2)
ggplot(dat, aes(gene, type, fill=type)) + geom_tile() + facet_grid(x~.)

编辑:也许你需要做一个马赛克图。在这种情况下,“ggmosaic”包可能是解决方案。它会给你一个看起来像这样的结果:

在此处输入图像描述

#To install:
devtools::install_github("haleyjeppson/ggmosaic")

library(ggmosaic)
ggplot(data=dat) + geom_mosaic(aes(x=product(x, gene), fill = type), divider = ddecker()) 

推荐阅读