I have a treemap that I've made using ggplot and treemapify. It's fine, but the legend is weirdly squashed - the labels are right up to the edges of the keys/symbols/icons. This doesn't happen with other plots so maybe it is a treemapify issue?
When I've searched for answers, most are about changing spacing between labels, for e.g., but that is not what I'm trying to do. I've found this one answer to what seems to be my question. And I guess I could add spaces to the labels! But it feels like there must be a better solution, especially because the labels are my column names and don't need spaces elsewhere, because for some reason the legend spacing is only an issue with this plot.
I've also tried theme(legend.text.align = 0.2)
, for e.g., but that clearly isn't right because it's about alignment, not margins or padding.
library(ggplot2)
library(treemapify)
tree_data <- as.data.frame(matrix(0, ncol = 0, nrow = 12))
tree_data$colour <- as.character(c("Red", "Red", "Blue", "Green"))
tree_data$shade <- as.character(c("Ruby", "Merlot", "Ink", "Olive",
"Garnet", "Wine", "Royal", "Emerald",
"Brick", "Berry", "Navy", "Apple"))
tree_data$freq <- sample(100, size = nrow(tree_data), replace = TRUE)
treeMapPlot <- ggplot(tree_data, aes(area = freq, fill = colour, label = shade,
subgroup = colour)) +
geom_treemap(color = "gray20") +
geom_treemap_subgroup_border() +
geom_treemap_text(colour = "white", place = "topleft", reflow = T, padding.x = grid::unit(1.5, "mm"),
padding.y = grid::unit(2, "mm"), size = 20) +
theme(plot.title = element_text(hjust = 0.5, size = 16),
legend.title = element_blank())
treeMapPlot
(Apologies for the colour mismatching!)
You can manually add a margin between the legend symbols and the text by specifying legend.spacing.x
within theme
. How about this:
treeMapPlot <- ggplot(tree_data, aes(area = freq, fill = colour, label = shade,
subgroup = colour)) +
geom_treemap(color = "gray20") +
geom_treemap_subgroup_border() +
geom_treemap_text(colour = "white", place = "topleft", reflow = T, padding.x = grid::unit(1.5, "mm"),
padding.y = grid::unit(2, "mm"), size = 20) +
theme(plot.title = element_text(hjust = 0.5, size = 16),
legend.title = element_blank(),
legend.spacing.x = unit(0.2, 'cm'))
treeMapPlot