r - 在具有不同条数的ggplot堆叠条形图中保持恒定条形宽度
问题描述
我想绘制一个ggplot2
具有固定条形宽度的堆叠条形图。问题是,当图的条数不同时,gridExtra::grid.arrange()
或其他函数(例如egg::ggarrange()
用较少的条数拉伸图),并且 bin 宽度会发生变化。有没有办法在所有地块中具有相同的 bin 宽度?我已经检查了其他几篇类似这样的帖子:geom_bar(position = "dodge") 中条形的宽度相同,但它们没有帮助!
注意:由于原始代码中的某些原因,我没有使用构面,并且我使用的是数据的简化版本。原始数据有50种类型和1000多个样本。
new <- data.frame(variable = rep(c('p 1', 'p 2', 'p 3'), 12+4+3),
value = sample(1:100, 3*12+3*4+3*3),
type = c(rep("A", 3*12), rep("B", 3*4), rep("C", 3*3)),
sample = rep(letters[1:(12+4+3)], each = 3))
my_plot <- function(my_type){
df <- subset(new, new$type %in% my_type)
gg <- ggplot(df) +
aes(group = 1)+
geom_bar(aes(colour = variable, fill = variable, y = value,
x = sample),
position="stack", stat="identity", width=.7) +
theme_classic() + theme(legend.position = 'None')
gg
}
p <- lapply(sort(unique(new$type)), my_plot)
g <- do.call(grid.arrange, c(p, ncol = 1))
解决方案
我将使用facet_grid()
两个示例供您考虑。也许他们可以满足您的兴趣:
library(ggplot2)
#Code 1
ggplot(new,aes(colour = variable, fill = variable, y = value,
x = sample)) +
geom_bar(position="stack", stat="identity", width=.7) +
theme_classic() + theme(legend.position = 'None')+
facet_grid(.~type,scales = 'free',space = 'free',drop = F)
输出:
第二个选项:
#Code 2
ggplot(new,aes(colour = variable, fill = variable, y = value,
x = sample)) +
geom_bar(position="stack", stat="identity", width=.7) +
theme_classic() + theme(legend.position = 'None')+
coord_flip()+
facet_grid(.~type,scales = 'free',space = 'free',drop = F)
输出:
在这两个示例中,条形宽度相等。
推荐阅读
- php - 使用 PCRE 从 Twig 模板中分离出前面的内容
- c++ - 如何为结构数组分配内存?
- java - 使用 lambda 将对象列表减少为不可变映射
- java - 在正整数和最大正整数之间打印倍数
- assembly - src 或 destination 中两个值的汇编语言含义
- javascript - 为什么这个 Promise.all() 即使在所有承诺都解决之后也没有解决?
- symfony - Symfony Workflow - 是否可以使用学说关系作为状态持有者?
- python-3.x - 我有一个关于我的程序的问题,它读取用户输入的 2 个句子,然后以各种方式比较它们
- graphviz - 节点的排名提供未排名的结果
- python - 请求发布字典格式错误的数据