ggplot图例键和使用treemapify的标签之间的间距

时间:2018-12-14 13:41:10

标签: r ggplot2 treemap

我有一个使用ggplot和treemapify制作的树图。很好,但是图例被怪异地挤压了-标签正好在按键/符号/图标的边缘。其他图不会发生这种情况,所以也许这是一个treemapify问题?

例如,当我搜索答案时,大多数都是关于更改标签之间的间距的,但这不是我要尝试的。我发现this似乎是我的问题的一个答案。而且我想我可以在标签上添加空格!但是感觉好像必须有一个更好的解决方案,特别是因为标签是我的列名,并且不需要在其他地方留空格,因为某些原因,图例间距只是此图的一个问题。

例如,我也尝试过theme(legend.text.align = 0.2),但这显然是不对的,因为它与对齐有关,而不是页边距或填充。

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

Example of issue

(对颜色不匹配表示歉意!)

1 个答案:

答案 0 :(得分:2)

您可以通过在legend.spacing.x中指定theme在图例符号和文本之间手动添加边距。怎么样:

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

enter image description here