我想向 ggplot 堆叠条形图添加一个组颜色条,就像 ComplexHeatmap 中的 left_annotation 一样。这是我的代码。预先感谢您!
library(ggplot2)
test <- as.data.frame(cbind(a = c(1, 1, 2, 3), b = 1:4, c = as.character(1:4)))
ggplot(test) +
geom_bar(aes(x = a, y = b, fill = c), stat = "identity") +
geom_bar(
aes(x = a, y = b, group = a),
stat = "summary", fun = sum,
fill = "transparent"
)+ coord_flip()
这是使用注释并调整剪切和边距的技巧:
library(ggplot2)
test <- data.frame(a = c(1, 1, 2, 3), b = 1:4, c = as.character(1:4))
ggplot(test) +
geom_col(aes(x = b, y = a, fill = c), orientation = "y") +
geom_bar(
aes(x = b, y = a, group = a),
orientation = "y",
stat = "summary", fun = sum,
fill = "transparent"
) +
annotate("rect", xmin = -0.8, xmax = -0.5,
ymin = 1.5, ymax = 3.5, fill = "orange") +
annotate("text", x = -0.6, y = 2.5, angle = 90, vjust = 0,
label = "Group2",
color = "orange4") +
coord_cartesian(xlim = c(0, NA), clip = "off") +
theme(plot.margin = unit(c(0.5, 0.5, 0.5, 5), "line"))