I'm looking to add an overarching grouping label to variables on the x-axis of geom_tile().
This is similar to the result I'm looking for:
However, the best I can come up with (WITHOUT using geom_text() and manually adding group 1, group 2 and group 3 above the x-axis variables) is this, which just creates a new variable containing both pieces on information:
set.seed(1)
df <- expand.grid(group = c("Group 1", "Group 2", "Group 3"),
xVar = c("A", "B"),
yVar = c("x","y","z")) %>%
mutate(fillValue = factor(sample(c(0,1), 18, TRUE))) %>%
mutate(group_and_xVar = paste(group, xVar, sep = "\n"))
ggplot(df, aes(x = group_and_xVar, y = yVar, fill = fillValue))
geom_tile(colour = "black")
scale_x_discrete(position = "top", expand = c(0,0))
scale_y_discrete(expand = c(0,0))
scale_fill_manual(values=c("#FF4933", "#72AF4A"))
labs(x = "", y = "", fill = "")
theme_bw()
theme(axis.text.x = element_text(angle = 0, vjust = .05),
legend.position = "none")
This is not what I want. I'd like to have each group only appear once on the plot and for the code to be soft coded (adaptable to new data or groups that might be added in the future). I've also attempted using facet_grid/facet_wrap but I haven't had luck with those.
Also adjusting the height of the cells to look more like the first image would be a bonus :)
CodePudding user response: