我正在使用特定参数集的条形图比较 3 个模型的结果。条形图是必要的,因为我只有 2 个模型的中位数和可信区间。我想用小提琴图替换或覆盖每组的第三条(显示每组模型 3 参数的边际后验)。我很乐意使用 base R、ggplot 或其他任何有效的东西!
到目前为止,我尝试过的简化版本如下:
library(ggplot2)
library(plyr)
## Data
params <- paste0("param", 1:3)
medians <- data.frame(value = c(seq(0.1,0.6, by = 0.1), rep(0, 3)),
model = rep(c("M1", "M2", "M3"), each = 3),
parameter = rep(paste0("param", 1:3), 3))
m3_posterior <- data.frame(value = runif(900, 0.2, 0.7),
model = "M3",
parameter = rep(params, each = 3))
m3_stats <- ddply(m3_posterior, .(parameter), summarize,
lower = quantile(value, 0.025),
upper = quantile(value, 0.975) )
confs <- data.frame(lower = c(seq(0.05, 0.55, by = 0.1), m3_stats$lower),
upper = c(seq(0.15, 0.65, by = 0.1), m3_stats$upper),
model = rep(c("M1", "M2", "M3"), each = 3),
parameter = rep(params, 3))
## plotting code
transparent_theme <- theme(
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank(),
axis.line = element_blank(),
panel.background = element_rect(fill = "transparent",colour = NA),
plot.background = element_rect(fill = "transparent",colour = NA))
print_list <- list()
for (param in 1 : length(params)) {
gg_medians <- subset(medians, parameter == params[param])
gg_confs <- subset(confs, parameter == params[param])
gg_post <- subset(m3_posterior, parameter == params[param])
p1 <- ggplot(gg_medians, aes(model, value)) +
geom_bar(stat="identity", fill = "white", colour = "black") +
geom_errorbar(data = gg_confs,
aes(y=upper, ymax=upper, ymin=lower)) +
scale_y_continuous(limits=c(0,1)) + labs(x=params[param])
p2 <- ggplot(gg_post, aes(parameter, value)) +
geom_violin(width=1.5, fill = NA)+
transparent_theme +
geom_errorbar(data = subset(gg_confs, model == "M3"),
aes(y=upper, ymax=upper, ymin=lower)) +
scale_y_continuous(limits=c(0,1)) + labs(x=params[param])
if (param > 1 ) {
p1 <- p1 + theme(axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank())
p2 <- p2 + theme(axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank())
}
p2_grob <- ggplotGrob(p2)
print_list[[param]] <- p1 + annotation_custom(grob = p2_grob,
xmin = 2.5, xmax = 3.5,
ymin = -0.0665, ymax = 1.061)
}
lay_out = function(...) {
x <- list(...)
n <- max(sapply(x, function(x) max(x[[2]])))
p <- max(sapply(x, function(x) max(x[[3]])))
grid::pushViewport(grid::viewport(layout = grid::grid.layout(n, p)))
for (i in seq_len(length(x))) {
print(x[[i]][[1]], vp = grid::viewport(
layout.pos.row = x[[i]][[2]],
layout.pos.col = x[[i]][[3]]))
}
}
lay_out(list(print_list[[1]], 1, 1),
list(print_list[[2]], 1, 2),
list(print_list[[3]], 1, 3))
我遇到的主要问题是:
将小提琴图 grob 与底层条形图对齐(我基本上使用猜测并检查数字)
保持每个图形的绘图区域相同,而第一个图形上只有 y 轴