我有来自多个
sample
的计数数据,这些数据映射到两个 class
、两个 group
和三个 type
:
library(dplyr)
set.seed(1)
df <- data.frame(type = c(rep("A",12), rep("B",12), rep("C",12)),
group = rep(c("O1","O1","O2","O2","O3","O3","Y1","Y1","Y2","Y2","Y3","Y3"),3),
class = rep(c("c1","c2"),18),
sample = rep(c("O1.c1_1","O1.c2_1","O2.c1_1","O2.c2_1","O3.c1_1","O3.c2_1",
"Y1.c1_1","Y1.c2_1","Y2.c1_1","Y2.c2_1","Y3.c1_1","Y3.c2_1"),3),
n = round(runif(36,10,50))) %>%
dplyr::group_by(type) %>% dplyr::mutate(type.n = sum(n)) %>%
dplyr::ungroup() %>% dplyr::mutate(f = n/type.n)
df$sample <- factor(df$sample, levels = c("O1.c1_1","O1.c2_1","O2.c1_1","O2.c2_1","O3.c1_1","O3.c2_1","Y1.c1_1","Y1.c2_1","Y2.c1_1","Y2.c2_1","Y3.c1_1","Y3.c2_1"))
df$class <- factor(df$class, levels = c("c1","c2"))
每个
sample
在其名称中编码了从中采样的 class
和 group
(例如,这些可能是单细胞 RNA-seq 样本,其中 class
对应于组织,group
对应于动物,type
对应细胞类型)。
我想将
sample
s' df$f
值绘制为堆积条形图,其中每个条形都是 type
,由 group
进行颜色编码,由 class
进行图案编码,并且我希望手动指定 group
(条形扇区)颜色以及图案颜色。
这是一个
data.frame
:
colors.df <- data.frame(group = levels(df$group),color = c("#55a189","#d27551","#7585a9","#ffa5ea","#c7ff64","#ffff38"))
我正在尝试
ggpattern
使用此代码:
library(ggplot2)
library(ggpattern)
ggplot(df, aes(type,f, fill = group))+
geom_bar_pattern(colour="black", position = "stack", stat = "identity", mapping = aes(pattern = class), linewidth = 0.15, pattern = "circle", pattern_density = 0.2, pattern_spacing = 0.01, pattern_angle = 120) +
scale_pattern_fill_manual(values = c(c1= 'black', c2 = 'white'))+
scale_pattern_color_manual(values = c(c1= 'black', c2 = 'white'))+
scale_fill_manual(values = colors.df$color)+
theme_minimal()
但不幸的是,它没有像我试图在命令中指定的那样对模式进行颜色编码。
有什么想法吗?
我想使用
R
ggplot2
作为堆叠条形图,其中每个条形都是一个
您有一些问题。首先,通过稍后在调用
pattern
时设置 class
来覆盖 pattern = "circle"
美学到 geom_bar_pattern
的映射。如果您只想使用不同颜色的圆圈作为图案填充,则需要指定 scale_pattern_manual
。其次,为了使条形段保持正确的顺序,您需要使用 group = interaction(class, group)
作为映射的一部分。第三,您的 scale_
调用没有执行任何操作,因为 pattern_fill
和 pattern_color
是您尚未映射的独立美学。最后,你还有一些冗余。 geom_bar(stat = "identity")
几年前已被 geom_col
取代,并且 position = "stack"
已成为默认设置。
解决这一切,我们有:
library(ggplot2)
library(ggpattern)
ggplot(df, aes(type,f, fill = group)) +
geom_col_pattern(aes(pattern = class, group = interaction(class, group),
pattern_fill = class, pattern_color = class),
linewidth = 0.15, pattern_density = 0.2,
pattern_spacing = 0.01, pattern_angle = 120) +
scale_pattern_fill_manual(values = c(c1 = 'black', c2 = 'white')) +
scale_pattern_color_manual(values = c(c1 = 'black', c2 = 'white')) +
scale_pattern_manual(values = c("circle", "circle")) +
scale_fill_manual(values = colors.df$color) +
theme_minimal(16)