我的数据与下面的示例数据类似,我正在尝试绘制基因型列上分面的测量列的直方图。最终,我希望条形的颜色以基因型和条件列为条件。
至关重要的是,基因型 B 个体从未在 L 条件下进行过测量。
数据如下:
library(ggplot2)
library(dplyr)
set.seed(123)
DF <- data.frame(Genotype = rep(c("A", "B"), 500),
Condition = sample(c("E", "L"), 1000, replace = T),
Measurment = round(rnorm(500,10,3), 0))
DF <- anti_join(DF, filter(DF, Genotype == "B" & Condition != "E"))'
head(DF)
Genotype Condition Measurment
1 A L 18
2 A L 2
3 B E 18
4 B E 18
5 B E 16
6 B E 16
现在我要指定条形的颜色,我认为创建一个新的十六进制代码列是最简单的,这样基因型 B 的所有个体都是一种颜色,如果在条件 E 和 a 下测量,基因型 A 的个体是第二种颜色如果在条件 L 下测量,则为第三种颜色。
DF <- DF %>% mutate(colr = ifelse(Genotype == "B", "#409ccd",
ifelse(Condition == "E", "#43cd80", "#ffc0cb")))
然后我可以在 Genotype 列上绘制一个多面直方图,如下所示:
ggplot(data=DF, aes(Measurment, fill = Condition)) +
geom_histogram(aes(y=..count.., fill = colr), position='dodge', binwidth = 1) +
facet_wrap(~Genotype, nrow=2) +
scale_fill_manual(values = c("#409ccd","#ffc0cb","#43cd80")) +
theme(legend.position="none")
就像这样:
但是,正如您所看到的,基因型 B 的列大小是基因型 A 的两倍。如何将基因型 B 缩小到与基因型 A 相同的大小?
我考虑向我的数据添加虚拟条目,其中基因型 B 具有条件 L 条目,但分箱功能随后将这些条目计为测量值,这是误导性的。我也有一个使用 geom_bar() 的版本,但这会导致类似的问题。 ggplot 必须有办法做到这一点。
感谢任何帮助。
最佳答案
也许是这样的?
ggplot(data=DF, aes(Measurment, fill = Condition)) +
geom_histogram(data=subset(DF, Genotype!="B"),aes(y=..count.., fill = colr), position='dodge', binwidth = 1) +
geom_histogram(data=subset(DF, Genotype=="B"),aes(x = Measurment, y=..count.., fill = colr), position=position_nudge(x=0.25), binwidth = 0.5) +
facet_wrap(~Genotype, nrow=2) +
scale_fill_identity() +
theme(legend.position="none")
关于r - 使用facet_wrap()在ggplot2直方图中相等的条形宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40649543/