I would like the levels of two different nested grouping variables to appear on separate lines below the plot, and not in the legend. What I have right now is this code:
Here's another solution using a package I'm working on for grouped bar charts (ggNestedBarChart):
data <- read.table(text = "Group Category Value
S1 A 73
S2 A 57
S3 A 57
S4 A 57
S1 B 7
S2 B 23
S3 B 57
S1 C 51
S2 C 57
S3 C 87", header = TRUE)
devtools::install_github("davedgd/ggNestedBarChart")
library(ggNestedBarChart)
library(scales)
p1 <- ggplot(data, aes(x = Category, y = Value/100, fill = Category), stat = "identity") +
geom_bar(stat = "identity") +
facet_wrap(vars(Category, Group), strip.position = "top", scales = "free_x", nrow = 1) +
theme_bw(base_size = 13) +
theme(panel.spacing = unit(0, "lines"),
strip.background = element_rect(color = "black", size = 0, fill = "grey92"),
strip.placement = "outside",
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
panel.grid.major.y = element_line(colour = "grey"),
panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_rect(color = "black", fill = NA, size = 0),
panel.background = element_rect(fill = "white"),
legend.position = "none") +
scale_y_continuous(expand = expand_scale(mult = c(0, .1)), labels = percent) +
geom_text(aes(label = paste0(Value, "%")), position = position_stack(0.5), color = "white", fontface = "bold")
ggNestedBarChart(p1)
ggsave("p1.png", width = 10, height = 5)
Note that ggNestedBarChart can group as many levels as necessary and isn't limited to just two (i.e., Category and Group in this example). For instance, using data(mtcars):
Code for this example is on the GitHub page.