I want to add a group color bar to ggplot stacked bar plot like the left_annotation in ComplexHeatmap. Here's my code. Thank you in advance!
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()
Here's a hack using an annotation and adjusting the clipping & margins:
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"))
If you want a more automated approach, facets or their variations (e.g. in ggh4x like this) would be more robust.